Friday, November 1, 2013

simple web service zend framework 2 | zf2

Hi all, Today I am going to code simple web service from ZF2.

As first step, you need to set up zf2 . Follow the instruction given in following link

http://framework.zend.com/manual/2.0/en/user-guide/skeleton-application.html

Mysoap is folder name of my new module. and it's place under root module on ZF2.

Copy all the folder from Application and past into Mysoap. Now we are ready to develop  our web service. see the below for folder structure


1.
C:\xampp\htdocs\ZendFramework\module\Mysoap\config\module.config.php

/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Mysoap;

use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;

class Module
{
    public function onBootstrap(MvcEvent $e)
    {
        $eventManager        = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);
    }

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                   
                ),
            ),
        );
    }
}


2.C:\xampp\htdocs\ZendFramework\module\Mysoap\src\Mysoap\Controller\IndexController.php

/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Mysoap\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;


use Zend\Soap\Client;
use Zend\Soap\Server;
use Zend\Soap\AutoDiscover;


require_once 'C:\xampp\htdocs\ZendFramework\module\Mysoap\src\Services\servicesAPI.php';



class IndexController extends AbstractActionController
{



    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {

        return new ViewModel();
    }

    public function soapAction()
    {

        // initialize server and set URI
        $server = new Server(null,
            array('uri' => 'http://myzend.local/mysoap/wsdl'));

        // set SOAP service class
        $server->setClass('servicesAPI');

        // handle request
        $server->handle();

        return $this->getResponse();
    }

    public function wsdlAction()
    {


        // set up WSDL auto-discovery
        $wsdl = new AutoDiscover();

        // attach SOAP service class
        $wsdl->setClass('servicesAPI');

        // set SOAP action URI
        $wsdl->setUri('http://myzend.local/mysoap/soap');

        // handle request
        $wsdl->handle();
        return $this->getResponse();
    }

    public function clientAction()
    {
        $url = 'http://myzend.local/mysoap/wsdl';

        $client = new Client($url);

        print_r($client->getProducts());


        return $this->getResponse();
    }


}

3. C:\xampp\htdocs\ZendFramework\module\Mysoap\config\module.config.php

return array(
    'controllers' => array(
        'invokables' => array(
            'Mysoap\Controller\Index' => 'Mysoap\Controller\IndexController',
        ),
    ),

    // The following section is new and should be added to your file
    'router' => array(
        'routes' => array(
            'album' => array(
                'type'    => 'segment',
                'options' => array(
                    'route'    => '/mysoap[/:action][/:id]',
                    'constraints' => array(
                        'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                        'id'     => '[0-9]+',
                    ),
                    'defaults' => array(
                        'controller' => 'Mysoap\Controller\Index',
                        'action'     => 'index',
                    ),
                ),
            ),
        ),
    ),

    'view_manager' => array(
        'template_path_stack' => array(
            'album' => __DIR__ . '/../view',
        ),
    ),
);

4. create new folder call Service under SRC. This our web service code
C:\xampp\htdocs\ZendFramework\module\Mysoap\src\Services\servicesAPI.php


class servicesAPI {
    /**
     * This method returns a string
     *
     * @param String $value
     * @return String
     */
    // define filters and validators for input
    private $_filters = array(
        'title'     => array('HtmlEntities', 'StripTags', 'StringTrim'),
        'shortdesc' => array('HtmlEntities', 'StripTags', 'StringTrim'),
        'price'     => array('HtmlEntities', 'StripTags', 'StringTrim'),
        'quantity'  => array('HtmlEntities', 'StripTags', 'StringTrim')
    );

    private $_validators = array(
        'title'     => array(),
        'shortdesc' => array(),
        'price'     => array('Float'),
        'quantity'  => array('Int')
    );

    /**
     * Returns list of all products in database
     *
     * @return array
     */
    public function getProducts()
    {

        $p = array(
            'title'     => 'Spinning Top',
            'shortdesc' => 'Hours of fun await with this colorful spinning top.
      Includes flashing colored lights.',
            'price'     => '3.99',
            'quantity'  => 57
        );
        return $p;

    }

    /**
     * Returns specified product in database
     *
     * @param integer $id
     * @return array|Example_Exception
     */
    public function getProduct($id)
    {
        $content = "some text here".$id;
        $fp = fopen("myText.txt","wb");
        fwrite($fp,$content);
        fclose($fp);

        return $id;
    }

    /**
     * Adds new product to database
     *
     * @param array $data array of data values with keys -> table fields
     * @return integer id of inserted product
     */
    public function addProduct($data)
    {

    }

    /**
     * Deletes product from database
     *
     * @param integer $id
     * @return integer number of products deleted
     */
    public function deleteProduct($id)
    {

    }

    /**
     * Updates product in database
     *
     * @param integer $id
     * @param array $data
     * @return integer number of products updated
     */
    public function updateProduct($id, $data)
    {

    }

}


10 comments:

  1. I'm trying test on ZF 2.2.5. Could you tell me which modified to run this example.
    Thank you so much.

    ReplyDelete
  2. I guess there is a wrong file path in the first step: It should be not "C:\xampp\htdocs\ZendFramework\module\Mysoap\config\module.config.php" but "C:\xampp\htdocs\ZendFramework\module\Mysoap\Module.php"

    ReplyDelete
  3. Did you copy & pasted the source code before modification from the zf2 tutorial? :) The Step 3 has a "album" as route.

    ReplyDelete
  4. Hi Good Article..
    can i know xmlrpc in zf2 like this

    ReplyDelete
  5. I really enjoyed reading your blog some post. coding explanation also good. I would like to visit here again. Keep writing and update some more tech posts..

    Thanks,
    Hire RoR Developers

    ReplyDelete
  6. Firstly I want to say thanks for the useful information that you are giving here on this post. Every time I come to this site, I always walk away with a lot of new knowledge.
    Engineering Colleges, ECE Engineering Colleges in Chennai

    ReplyDelete
  7. A very well-written post. I read and liked the post and have also bookmarked you. All the best for future endeavors. Getting some solution regarding.
    UI Design Companies in Bangalore, Web Application Development Companies in Bangalore

    ReplyDelete