RESTful modules in zf2

Corley S.r.l.
Corley S.r.l.Corley S.r.l.
RESTful Modules in ZF2
Walter Dal Mut – walter.dalmut@gmail.com - @walterdalmut
               https://github.com/wdalmut




                @walterdalmut - www.corley.it - www.upcloo.com
About Me
                      • Walter Dal Mut (@walterdalmut)
                      • Electronic Engineer
                            • Polytechnic University of Turin
                      • Startupper
                            • Corley S.r.l. – www.corley.it
                                   • Cloud Computing Services
                            • UpCloo Ltd. – www.upcloo.com
                                   • Semantic Most Related Links service




           @walterdalmut - www.corley.it - www.upcloo.com
Summary
• REST introduction
• REST constraints
• Types of RESTful services
• ZF2 RESTful modules
   • RESTful ZF2 URI tunneling module
   • RESTful ZF2 CRUD module




                           @walterdalmut - www.corley.it - www.upcloo.com
RESTful? What it means in few words…
• Representational State Transfer (REST)

• Architecture is based on Client-Server
   • Clients initiate requests to servers; servers process requests and return
     appropriate responses
• Flexible, the application must know messages format
   • XML
   • JSON
   • Etc.


                             @walterdalmut - www.corley.it - www.upcloo.com
RESTful services are resource centric
• Resources (sources of specific information)
• Each resource is referenced with a global identifier (URI, etc.)
• Any number of connectors can mediate the request
   •   Clients
   •   Servers
   •   Caches
   •   Tunnels




                          @walterdalmut - www.corley.it - www.upcloo.com
REST Constraints
• Client-Server
   • A uniform interface separates clients from servers.
• Stateless
   • The client–server communication is further constrained by no client context being
     stored on the server between requests.
• Cacheable
   • Clients can cache responses
• Layered System
   • Intermediary servers may improve system scalability by enabling load-balancing and
     by providing shared caches. They may also enforce security policies.
• Uniform interface
   • Simplify and decouples the architecture


                               @walterdalmut - www.corley.it - www.upcloo.com
Several types of RESTful services
• URI Templates
   • http://rest.domain.tld/order/{orderID}
   • One of the major uses for URI templates is as human- and machine-readable
     documentation.
• URI Tunneling
   • http://rest.domain.tld/PlaceOrder?pizza=margherita&type=classic
      • Rest.domain.tld  service
      • PlaceOrder method
      • Pizza=margherita&type=classic  arguments
• POX – Plain Old XML over HTTP
   • Similar to URI Tunneling but information will be sent as XML document in the
     HTTP request from the customer.
                             @walterdalmut - www.corley.it - www.upcloo.com
POX – Plain Old XML over HTTP
   example
                     POST /PlaceOrder HTTP/1.1
                     Content-Type: application/xml
Client application                                                                         Application domain
                     <Order>
                       <Pizza>
                         <Name>margherita</Name>
                         <Type>classic</Type>
                       </Pizza>
                     </Order>

                     HTTP/1.1 200 OK

                     <OrderConfirmation>
                       <OrderID>1345</OrderID>
                     </OrderConfirmation>




                                          @walterdalmut - www.corley.it - www.upcloo.com
CRUD Webservices
• CRUD what it means?
   • Create, Read, Update and Delete
   • Patterns for manipulating resources across the network
• Extended usage of HTTP verbs
   •   GET
   •   POST
   •   PUT
   •   DELETE
• Using HTTP as an application protocol instead of a transport protocol
   • Web is really a big framework for building distributed systems.

                            @walterdalmut - www.corley.it - www.upcloo.com
HTTP verbs in CRUD services
• Get Read Operation
   • Used to retrive resource details
   • http://rest.service.tld/order/10
• Post  Create Operation
   • Used to create new resources
• Put Update Operation
   • Used to update existing resources
• Delete Delete Operation
   • Used to delete existing resources

POST/PUT can be exchanged and sometimes PUT/DELETE can be excluded to
enable javascript integration (PUT/DELETE not supported browser side
[HTTP_X_HTTP_METHOD_OVERRIDE parameter])

                                 @walterdalmut - www.corley.it - www.upcloo.com
CRUD Summary

Verb     URI or Template   Use
POST     /order            Create a new order, and upon success, receive a Location header specifying the
                           new order’s URI.
GET      /order/{id}       Request the current state of the order specified by the
                           URI.
PUT      /order/{id}       Update an order at the given URI with new information,
                           providing the full representation.
DELETE   /order/{id}       Logically remove the order identified by the given URI.




                                 @walterdalmut - www.corley.it - www.upcloo.com
Status code definition (short list)
• 2xx (Positives)
    • 200 OK – The request has succeeded.
    • 201 Created – The server accept the request and it has created the resource.
    • 202 Accepted – The request has been accepted for processing, but the processing has not been completed.
• 4xx (Client Errors)
    •   400 Bad Request – The request could not be understood by the server due to malformed syntax.
    •   401 Unauthorized – The request requires user authentication.
    •   403 Forbidden – The server understood the request, but is refusing to fulfill it.
    •   404 Not found – The server has not found anything matching the Request-URI.
    •   405 Method not allowed – The method specified in the Request-Line is not allowed for the resource identified
        by the Request-URI.
• 5xx (Server Errors)
    • 500 Internal Server Error – The server encountered an unexpected condition which prevented it from fulfilling
      the request.
    • 501 Not implemented – The server does not support the functionality required to fulfill the request.
    • 503 Service unavailable – The server is currently unable to handle the request due to a temporary overloading
      or maintenance of the server.

                                        @walterdalmut - www.corley.it - www.upcloo.com
RESTful module idea
                                                             • Router
                                                                • Wire requests to RESTful controllers
                                                             • RESTful Controllers
requests      Router                                            • Uses HTTP verbs to call dedicated
                                                                   actions
                                                                • Query models in order to serve
                          RESTful                                  responses
                                            Models           • POST Processors
                         Controllers
                                                                • Create valid messages using formats
                                                                      • JSON
 Responses     POST                                                   • XML
             Processor                                                • Etc.




                             @walterdalmut - www.corley.it - www.upcloo.com
Realize ZF2 tunneling RESTful module
• ZF1 provides «Zend_Rest_Server» that realize URI tunneling
• We can realize the same thing in 2 minutes thanks to ZF2 flexibility.

• We need to configure
   • Router
   • Events

• A simple example here:
   • https://github.com/wdalmut/ZF2-Tunneling-Restful-Module-Skeleton

                           @walterdalmut - www.corley.it - www.upcloo.com
ZF2 URI Tunneling - Configuration
<?php
return array(                                                                              We have created a simple base route «/tunnel»
    'controllers' => array(
        'invokables' => array(                                                             and a dynamic rule that select a «model» and an
          'index' => 'TunnelingRestController',
        )                                                                                  attached «action»
    ),
    'router' => array(
        'routes' => array(
             'tunneling' => array(                                                         In simple words
                 'type' => 'ZendMvcRouterHttpSegment',
                 'options' => array(                                                       • http://my-app.local/tunnel/menu/get?id=1
                     'route' => '/tunnel',
                     'defaults' => array(                                                  • «menu»
                         'controller' => 'index',
                         'action' => 'index'                                                    • The model «TunnelingModelMenu»
                     ),
                 ),                                                                        • «get»
                 'may_terminate' => true,
                 'child_routes' => array(                                                       • The model action «get()»
                     'default' => array(
                         'type' => 'ZendMvcRouterHttpSegment',                         • «id=1>
                         'options' => array(
                             'route' => '[/:model/:action]',                                    • The action parameters «get(1)»
                             'constraints' => array(
                                 'controller' => 'index',
                                 'model' => '[a-zA-Z][a-zA-Z0-9_]*',
                                 'action' => '[a-zA-Z][a-zA-Z0-9_]*'
                             ),
                         ),
                     ),
                 ),
             ),
        ),
    )
);
                                                           @walterdalmut - www.corley.it - www.upcloo.com
ZF2 URI Tunneling - Controller
<?php
namespace TunnelingRest;                                                                        The base «AbstractController» is very flexible
Use …                                                                                            and enable us to use the «dispatch» action to
class Controller extends AbstractController                                                      realize what we need in few lines.
{
    public function onDispatch(MvcEvent $e)
    {
        $routeMatch = $e->getRouteMatch();                                                       In practice we allocate the model and call the
        $params = $routeMatch->getParams();
        $vars = get_object_vars($e->getRequest()->getQuery());                                   requested action. The return variable is used as
        $filter = new ZendFilterFilterChain();                                                response.
        $filter->attach(new ZendFilterWordDashToCamelCase());
        $filter->attach(new ZendFilterCallback("lcfirst"));
        $action = $filter->filter($params["action"]);
        $filter->attach(new ZendFilterCallback("ucfirst"));                                   In case of missing model or missing action an
        $model = $filter->filter($params["model"]);
                                                                                                 «InvalidArgumentException» is thrown.
        $classname = "TunnelingModel{$model}";
        if (class_exists($classname)) {
            $clazz = new $classname;
            if (property_exists($clazz, $action)) {
                 $ret = call_user_func_array(array($clazz, $action), $vars);
                 $e->setResult($ret);
                 return;
            } else {
                 throw new InvalidArgumentException("Method "{$action}" doesn't exists'");
            }
        } else {
            throw new InvalidArgumentException("Class "{$classname}" doesn't exists'");
        }
    }
}
                                                                 @walterdalmut - www.corley.it - www.upcloo.com
ZF2 URI Tunneling – Model example
<?php
namespace TunnelingModel;                                                                   As you can see, the «model» is a simple class
                                                                                             definition.
class Menu
{
    public function get($id)
    {                                                                                        • /tunnel/menu/get?id=1
        return array("id" => $id);
    }                                                                                        • /tunnel/menu/add?x=pizza&y=4
    public function add($name, $value)
    {                                                                                        Very simple implementation
        return array("name" => $name, "value" => $value);
    }
}




                                                            @walterdalmut - www.corley.it - www.upcloo.com
ZF2 URI Tunneling – JSON responses
<?php
namespace Tunneling;
                                                                                              Thanks to events we can wire controller output
use ZendMvcMvcEvent;
                                                                                              to a post processor that converts responses in
class Module
                                                                                              json messages.
{
    public function onBootstrap($e)
    {
        /** @var ZendModuleManagerModuleManager $moduleManager */
                                                                                              • Attach a «postProcess» action and create a
        $moduleManager = $e->getApplication()->getServiceManager()->get('modulemanager');
        /** @var ZendEventManagerSharedEventManager $sharedEvents */
                                                                                                json message.
        $sharedEvents = $moduleManager->getEventManager()->getSharedManager();


          $sharedEvents->attach(
              'ZendMvcControllerAbstractController',
              MvcEvent::EVENT_DISPATCH,
              array($this, 'postProcess'),
              -100
          );
      }
//…
      public function postProcess(MvcEvent $e)
      {
          $routeMatch = $e->getRouteMatch();
          if (strpos($routeMatch->getMatchedRouteName(), "tunneling") !== false) {
              $e->getResponse()->setContent(json_encode($e->getResult()->getVariables()));
              return $e->getResponse();
          }
      }
}


                                                             @walterdalmut - www.corley.it - www.upcloo.com
ZF2 RESTful CRUD modules
• ZF2 provides a base controller class that can help us to realize RESTful
  modules in few steps
   • ZendMvcControllerAbstractRestfulController

• CRUD based implementation (Extended)
   •   get($id)
   •   delete($id)
   •   update($id)
   •   create($id)


                           @walterdalmut - www.corley.it - www.upcloo.com
ZF2 RESTful CRUD module example
• Clone ZF2 Skeleton Application
   • Git clone https://github.com/zendframework/ZendSkeletonApplication.git my-app
   • Git submodule init
   • Git submodule update
• Clone a ZF2 RESTful module
   • Git submodule add https://github.com/wdalmut/ZF2-Restful-Module-Skeleton.git module/Main
• Add «Main» module into «configs/application.config.php»
• Create you application virtual host and try it
   •   http://my-app.local/rest/info/json                                              [getList]
   •   http://my-app.local/rest/info/json/1                                            [get]
   •   curl –X POST –d ‘hello=world’ http://my-app.local/rest/info                     [create]
   •   curl –X PUT –d ‘hello=ciao’ http://my-app.local/rest/info/1                     [update]
   •   curl –X DELETE http://my-app.local/rest/info/1                                  [delete]

                                      @walterdalmut - www.corley.it - www.upcloo.com
RESTful Controllers
<?php
                                                         • RESTful Controller should extends AbstractRestfulController
namespace MainController;
                                                            • 5 abstract methods (CRUD + List)
use ZendMvcControllerAbstractRestfulController;
                                                                 • getList
class InfoController extends AbstractRestfulController
{                                                                     • GET operation without parameters
    public function getList()
    {                                                                 • /rest/json/info
    }
        return array('ciao' => 'mondo');
                                                                 • Get
    public function get($id)                                          • READ resource with parameters (ID)
    {
                                                                      • /rest/json/info/1
    }
                                                                 • Delete
    public function delete($id)
    {                                                                 • DELETE a resource
    }                                                            • Update
    public function update($id, $data)                                • UPDATE a resource
    {
                                                                 • Create
    }
                                                                      • CREATE a new resource
    public function create($data = null)
    {

    }
}


                                                          @walterdalmut - www.corley.it - www.upcloo.com
First of all play with routes
'router' => array(
    'routes' => array(                                                  • Create a base route /rest that enable also formatters
        'restful' => array(
            'type' => 'ZendMvcRouterHttpSegment',                       • Formatter allow us to switch easly to JSON,
            'options' => array(
                'route' => '/rest[/:formatter]',
                                                                               XML etc.
                'constraints' => array(                                 • Child routes play with controller and identifiers
                    'formatter' => '[a-zA-Z0-9_-]*',
                ),
            ),
            'may_terminate' => true,
            'child_routes' => array(
                'default' => array(
                    'type' => 'ZendMvcRouterHttpSegment',
                    'options' => array(
                        'route' => '[/:controller[/:id]]',
                        'constraints' => array(
                            'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
                            'id' => '[a-zA-Z0-9_-]*'
                        ),
                    ),
                ),
            ),
        ),
    ),




                                                @walterdalmut - www.corley.it - www.upcloo.com
Formatters
• RESTful services can handle different type of messages
   •   JSON
   •   XML
   •   Images
   •   Etc
• The high modularity of ZF2 MVC implementation enable us to add
  different layers of abstractions and formatters is one of this.
   • Client must know what kind of messages type have to handle.
   • Post Processors are used to render messages


                           @walterdalmut - www.corley.it - www.upcloo.com
Formatters «configs/module.config.php»
'errors' => array(
    'post_processor' => 'json-pp',                      • The configuration allows us to define different «post processors»
    'show_exceptions' => array(
        'message' => true,
                                                        • Errors can be detailed more, for example traces, messages etc.
        'trace' => true
    )
),
'di' => array(
    'instance' => array(
        'alias' => array(
            'json-pp' => 'MainPostProcessorJson',
            'jsonp-pp' => 'MainPostProcessorJsonp',
            'image-pp' => 'MainPostProcessorImage'
        )
    )
),




                                                @walterdalmut - www.corley.it - www.upcloo.com
Wiring events (Module.php)
/**
 * @param MvcEvent $e
 */
 public function onBootstrap($e)
                                                                                                     • Event position -100
 {
     /** @var ZendModuleManagerModuleManager $moduleManager */
                                                                                                         • Handle post processors
     $moduleManager = $e->getApplication()->getServiceManager()->get('modulemanager');
     /** @var ZendEventManagerSharedEventManager $sharedEvents */
                                                                                                     • Event position 100
     $sharedEvents = $moduleManager->getEventManager()->getSharedManager();
                                                                                                         • Handle HTTP Method Override
     $sharedEvents->attach(
                                                                                                     • Event position 999
         'ZendMvcControllerAbstractRestfulController',
         MvcEvent::EVENT_DISPATCH,
                                                                                                         • Handle errors
         array($this, 'postProcess'),
         -100
     );


     $sharedEvents->attach(
         'MainControllerInfoController',
         MvcEvent::EVENT_DISPATCH,
         array($e->getApplication()->getServiceManager()->get('MainHttpRestful'), 'onDispatch'),
         100
     );


     $sharedEvents->attach(
         'ZendMvcApplication',
         MvcEvent::EVENT_DISPATCH_ERROR,
         array($this, 'errorProcess'),
         999
     );
 }

                                                       @walterdalmut - www.corley.it - www.upcloo.com
Attach Post Processor to Actions
public function postProcess(MvcEvent $e)
{
    $routeMatch = $e->getRouteMatch();
    $formatter = $routeMatch->getParam('formatter', false);

    $di = $e->getTarget()->getServiceLocator()->get('di');

    if ($formatter !== false) {
        if ($e->getResult() instanceof ZendViewModelViewModel) {
            if (($e->getResult()->getVariables())) {
                $vars = $e->getResult()->getVariables();
            } else {
                $vars = null;
            }
        } else {
            $vars = $e->getResult();
        }

        $postProcessor = $di->get($formatter . '-pp', array(
            'request' => $e->getRequest(),
            'response' => $e->getResponse(),
            'vars' => $vars,
        ));

        $postProcessor->process();

        return $postProcessor->getResponse();
    }

    return null;
}



                                                       @walterdalmut - www.corley.it - www.upcloo.com
Example of JSON Post Processor
<?php
                                                                       <?php
namespace MainPostProcessor;
                                                                       namespace MainPostProcessor;
/**
                                                                       abstract class AbstractPostProcessor
 *
                                                                       {
 */
                                                                           protected $_vars = null;
class Json extends AbstractPostProcessor
                                                                           private $_request = null;
{
                                                                           private $_response = null;
    public function process()
    {
                                                                           public function __construct
        $result = json_encode($this->_vars);
                                                                               (ZendHttpRequest $request, ZendHttpResponse $response, $vars = null)
                                                                           {
        $headers = $this->getResponse()->getHeaders();
                                                                               $this->_vars = $vars;
        $headers->addHeaderLine('Content-Type', 'application/json');
                                                                               $this->_response = $response;
                                                                               $this->_request = $request;
        $this->getResponse()->setHeaders($headers);
                                                                           }
        $this->getResponse()->setContent($result);
    }
                                                                           public function getResponse()
}
                                                                           {
                                                                               return $this->_response;
                                                                           }

                                                                           public function getRequest()
                                                                           {
                                                                               return $this->_request;
                                                                           }

                                                                           abstract public function process();
                                                                       }




                                                          @walterdalmut - www.corley.it - www.upcloo.com
ZF2 RESTful Modules
            Thanks for listening…



                  Any questions?




            @walterdalmut - www.corley.it - www.upcloo.com
1 of 28

Recommended

Rest api design by george reese by
Rest api design by george reeseRest api design by george reese
Rest api design by george reesebuildacloud
105.5K views24 slides
Best Practices in Web Service Design by
Best Practices in Web Service DesignBest Practices in Web Service Design
Best Practices in Web Service DesignLorna Mitchell
40.5K views38 slides
The never-ending REST API design debate by
The never-ending REST API design debateThe never-ending REST API design debate
The never-ending REST API design debateRestlet
10.1K views93 slides
REST API Design & Development by
REST API Design & DevelopmentREST API Design & Development
REST API Design & DevelopmentAshok Pundit
1.2K views26 slides
Securty Testing For RESTful Applications by
Securty Testing For RESTful ApplicationsSecurty Testing For RESTful Applications
Securty Testing For RESTful ApplicationsSource Conference
15.2K views30 slides
Rest api standards and best practices by
Rest api standards and best practicesRest api standards and best practices
Rest api standards and best practicesAnkita Mahajan
7.2K views19 slides

More Related Content

What's hot

REST API Design for JAX-RS And Jersey by
REST API Design for JAX-RS And JerseyREST API Design for JAX-RS And Jersey
REST API Design for JAX-RS And JerseyStormpath
12.6K views79 slides
Best Practices for Architecting a Pragmatic Web API. by
Best Practices for Architecting a Pragmatic Web API.Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.Mario Cardinal
47.6K views38 slides
RESTful API Automation with JavaScript by
RESTful API Automation with JavaScriptRESTful API Automation with JavaScript
RESTful API Automation with JavaScriptJonathan LeBlanc
5.5K views22 slides
Understanding and testing restful web services by
Understanding and testing restful web servicesUnderstanding and testing restful web services
Understanding and testing restful web servicesmwinteringham
2.2K views59 slides
Restful api design by
Restful api designRestful api design
Restful api designMizan Riqzia
1.5K views29 slides
RESTful services by
RESTful servicesRESTful services
RESTful servicesgouthamrv
4.5K views57 slides

What's hot(19)

REST API Design for JAX-RS And Jersey by Stormpath
REST API Design for JAX-RS And JerseyREST API Design for JAX-RS And Jersey
REST API Design for JAX-RS And Jersey
Stormpath12.6K views
Best Practices for Architecting a Pragmatic Web API. by Mario Cardinal
Best Practices for Architecting a Pragmatic Web API.Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.
Mario Cardinal47.6K views
RESTful API Automation with JavaScript by Jonathan LeBlanc
RESTful API Automation with JavaScriptRESTful API Automation with JavaScript
RESTful API Automation with JavaScript
Jonathan LeBlanc5.5K views
Understanding and testing restful web services by mwinteringham
Understanding and testing restful web servicesUnderstanding and testing restful web services
Understanding and testing restful web services
mwinteringham2.2K views
Restful api design by Mizan Riqzia
Restful api designRestful api design
Restful api design
Mizan Riqzia1.5K views
RESTful services by gouthamrv
RESTful servicesRESTful services
RESTful services
gouthamrv4.5K views
Elegant Rest Design Webinar by Stormpath
Elegant Rest Design WebinarElegant Rest Design Webinar
Elegant Rest Design Webinar
Stormpath3.7K views
Rest & RESTful WebServices by Prateek Tandon
Rest & RESTful WebServicesRest & RESTful WebServices
Rest & RESTful WebServices
Prateek Tandon5.8K views
Learn REST in 18 Slides by Suraj Gupta
Learn REST in 18 SlidesLearn REST in 18 Slides
Learn REST in 18 Slides
Suraj Gupta43.9K views
Building Beautiful REST APIs with ASP.NET Core by Stormpath
Building Beautiful REST APIs with ASP.NET CoreBuilding Beautiful REST APIs with ASP.NET Core
Building Beautiful REST APIs with ASP.NET Core
Stormpath2.2K views
REST-API introduction for developers by Patrick Savalle
REST-API introduction for developersREST-API introduction for developers
REST-API introduction for developers
Patrick Savalle5.5K views
Best Practice in Web Service Design by Lorna Mitchell
Best Practice in Web Service DesignBest Practice in Web Service Design
Best Practice in Web Service Design
Lorna Mitchell2K views

Similar to RESTful modules in zf2

BeJUG JAX-RS Event by
BeJUG JAX-RS EventBeJUG JAX-RS Event
BeJUG JAX-RS EventStephan Janssen
1.4K views77 slides
Solr Powered Lucene by
Solr Powered LuceneSolr Powered Lucene
Solr Powered LuceneErik Hatcher
6.6K views64 slides
Rest presentation by
Rest  presentationRest  presentation
Rest presentationsrividhyau
5.1K views19 slides
Apache Solr crash course by
Apache Solr crash courseApache Solr crash course
Apache Solr crash courseTommaso Teofili
25.6K views72 slides
An Overview of Web Services: SOAP and REST by
An Overview of Web Services: SOAP and REST An Overview of Web Services: SOAP and REST
An Overview of Web Services: SOAP and REST Ram Awadh Prasad, PMP
3.6K views30 slides
On being RESTful by
On being RESTfulOn being RESTful
On being RESTfulFabio Mancinelli
1.8K views49 slides

Similar to RESTful modules in zf2(20)

Solr Powered Lucene by Erik Hatcher
Solr Powered LuceneSolr Powered Lucene
Solr Powered Lucene
Erik Hatcher6.6K views
Rest presentation by srividhyau
Rest  presentationRest  presentation
Rest presentation
srividhyau5.1K views
Microservices with Apache Camel, Docker and Fabric8 v2 by Christian Posta
Microservices with Apache Camel, Docker and Fabric8 v2Microservices with Apache Camel, Docker and Fabric8 v2
Microservices with Apache Camel, Docker and Fabric8 v2
Christian Posta8.4K views
Servletarchitecture,lifecycle,get,post by vamsitricks
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
vamsitricks9.6K views
REST Methodologies by jrodbx
REST MethodologiesREST Methodologies
REST Methodologies
jrodbx1.2K views
Meetup on Apache Zookeeper by Anshul Patel
Meetup on Apache ZookeeperMeetup on Apache Zookeeper
Meetup on Apache Zookeeper
Anshul Patel678 views
Servletarchitecture,lifecycle,get,post by vamsi krishna
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
vamsi krishna2.6K views
Servletarchitecture,lifecycle,get,post by vamsitricks
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
vamsitricks3.4K views
Global Scale ESB with Mule by Andrew Kennedy
Global Scale ESB with MuleGlobal Scale ESB with Mule
Global Scale ESB with Mule
Andrew Kennedy1.9K views
Web Technologies in Java EE 7 by Lukáš Fryč
Web Technologies in Java EE 7Web Technologies in Java EE 7
Web Technologies in Java EE 7
Lukáš Fryč2.2K views
Exploring Twitter's Finagle technology stack for microservices by 💡 Tomasz Kogut
Exploring Twitter's Finagle technology stack for microservicesExploring Twitter's Finagle technology stack for microservices
Exploring Twitter's Finagle technology stack for microservices
💡 Tomasz Kogut3.2K views
IT talk SPb "Full text search for lazy guys" by DataArt
IT talk SPb "Full text search for lazy guys" IT talk SPb "Full text search for lazy guys"
IT talk SPb "Full text search for lazy guys"
DataArt740 views

More from Corley S.r.l.

Aws rekognition - riconoscimento facciale by
Aws rekognition  - riconoscimento faccialeAws rekognition  - riconoscimento facciale
Aws rekognition - riconoscimento faccialeCorley S.r.l.
313 views18 slides
AWSome day 2018 - scalability and cost optimization with container services by
AWSome day 2018 - scalability and cost optimization with container servicesAWSome day 2018 - scalability and cost optimization with container services
AWSome day 2018 - scalability and cost optimization with container servicesCorley S.r.l.
273 views34 slides
AWSome day 2018 - API serverless with aws by
AWSome day 2018  - API serverless with awsAWSome day 2018  - API serverless with aws
AWSome day 2018 - API serverless with awsCorley S.r.l.
203 views38 slides
AWSome day 2018 - database in cloud by
AWSome day 2018 -  database in cloudAWSome day 2018 -  database in cloud
AWSome day 2018 - database in cloudCorley S.r.l.
195 views36 slides
Trace your micro-services oriented application with Zipkin and OpenTracing by
Trace your micro-services oriented application with Zipkin and OpenTracing Trace your micro-services oriented application with Zipkin and OpenTracing
Trace your micro-services oriented application with Zipkin and OpenTracing Corley S.r.l.
1.3K views46 slides
Apiconf - The perfect REST solution by
Apiconf - The perfect REST solutionApiconf - The perfect REST solution
Apiconf - The perfect REST solutionCorley S.r.l.
305 views14 slides

More from Corley S.r.l.(20)

Aws rekognition - riconoscimento facciale by Corley S.r.l.
Aws rekognition  - riconoscimento faccialeAws rekognition  - riconoscimento facciale
Aws rekognition - riconoscimento facciale
Corley S.r.l.313 views
AWSome day 2018 - scalability and cost optimization with container services by Corley S.r.l.
AWSome day 2018 - scalability and cost optimization with container servicesAWSome day 2018 - scalability and cost optimization with container services
AWSome day 2018 - scalability and cost optimization with container services
Corley S.r.l.273 views
AWSome day 2018 - API serverless with aws by Corley S.r.l.
AWSome day 2018  - API serverless with awsAWSome day 2018  - API serverless with aws
AWSome day 2018 - API serverless with aws
Corley S.r.l.203 views
AWSome day 2018 - database in cloud by Corley S.r.l.
AWSome day 2018 -  database in cloudAWSome day 2018 -  database in cloud
AWSome day 2018 - database in cloud
Corley S.r.l.195 views
Trace your micro-services oriented application with Zipkin and OpenTracing by Corley S.r.l.
Trace your micro-services oriented application with Zipkin and OpenTracing Trace your micro-services oriented application with Zipkin and OpenTracing
Trace your micro-services oriented application with Zipkin and OpenTracing
Corley S.r.l.1.3K views
Apiconf - The perfect REST solution by Corley S.r.l.
Apiconf - The perfect REST solutionApiconf - The perfect REST solution
Apiconf - The perfect REST solution
Corley S.r.l.305 views
Apiconf - Doc Driven Development by Corley S.r.l.
Apiconf - Doc Driven DevelopmentApiconf - Doc Driven Development
Apiconf - Doc Driven Development
Corley S.r.l.202 views
Authentication and authorization in res tful infrastructures by Corley S.r.l.
Authentication and authorization in res tful infrastructuresAuthentication and authorization in res tful infrastructures
Authentication and authorization in res tful infrastructures
Corley S.r.l.278 views
Flexibility and scalability of costs in serverless infrastructures by Corley S.r.l.
Flexibility and scalability of costs in serverless infrastructuresFlexibility and scalability of costs in serverless infrastructures
Flexibility and scalability of costs in serverless infrastructures
Corley S.r.l.174 views
CloudConf2017 - Deploy, Scale & Coordinate a microservice oriented application by Corley S.r.l.
CloudConf2017 - Deploy, Scale & Coordinate a microservice oriented applicationCloudConf2017 - Deploy, Scale & Coordinate a microservice oriented application
CloudConf2017 - Deploy, Scale & Coordinate a microservice oriented application
Corley S.r.l.325 views
A single language for backend and frontend from AngularJS to cloud with Clau... by Corley S.r.l.
A single language for backend and frontend  from AngularJS to cloud with Clau...A single language for backend and frontend  from AngularJS to cloud with Clau...
A single language for backend and frontend from AngularJS to cloud with Clau...
Corley S.r.l.349 views
AngularJS: Service, factory & provider by Corley S.r.l.
AngularJS: Service, factory & providerAngularJS: Service, factory & provider
AngularJS: Service, factory & provider
Corley S.r.l.1.5K views
The advantage of developing with TypeScript by Corley S.r.l.
The advantage of developing with TypeScript The advantage of developing with TypeScript
The advantage of developing with TypeScript
Corley S.r.l.1.3K views
Angular coding: from project management to web and mobile deploy by Corley S.r.l.
Angular coding: from project management to web and mobile deployAngular coding: from project management to web and mobile deploy
Angular coding: from project management to web and mobile deploy
Corley S.r.l.893 views
Corley cloud angular in cloud by Corley S.r.l.
Corley cloud   angular in cloudCorley cloud   angular in cloud
Corley cloud angular in cloud
Corley S.r.l.801 views
Measure your app internals with InfluxDB and Symfony2 by Corley S.r.l.
Measure your app internals with InfluxDB and Symfony2Measure your app internals with InfluxDB and Symfony2
Measure your app internals with InfluxDB and Symfony2
Corley S.r.l.4.5K views
Read Twitter Stream and Tweet back pictures with Raspberry Pi & AWS Lambda by Corley S.r.l.
Read Twitter Stream and Tweet back pictures with Raspberry Pi & AWS LambdaRead Twitter Stream and Tweet back pictures with Raspberry Pi & AWS Lambda
Read Twitter Stream and Tweet back pictures with Raspberry Pi & AWS Lambda
Corley S.r.l.3.6K views
Deploy and Scale your PHP App with AWS ElasticBeanstalk and Docker- PHPTour L... by Corley S.r.l.
Deploy and Scale your PHP App with AWS ElasticBeanstalk and Docker- PHPTour L...Deploy and Scale your PHP App with AWS ElasticBeanstalk and Docker- PHPTour L...
Deploy and Scale your PHP App with AWS ElasticBeanstalk and Docker- PHPTour L...
Corley S.r.l.6.3K views
Middleware PHP - A simple micro-framework by Corley S.r.l.
Middleware PHP - A simple micro-frameworkMiddleware PHP - A simple micro-framework
Middleware PHP - A simple micro-framework
Corley S.r.l.8.3K views

Recently uploaded

1st parposal presentation.pptx by
1st parposal presentation.pptx1st parposal presentation.pptx
1st parposal presentation.pptxi238212
9 views3 slides
AMAZON PRODUCT RESEARCH.pdf by
AMAZON PRODUCT RESEARCH.pdfAMAZON PRODUCT RESEARCH.pdf
AMAZON PRODUCT RESEARCH.pdfJerikkLaureta
19 views13 slides
Tunable Laser (1).pptx by
Tunable Laser (1).pptxTunable Laser (1).pptx
Tunable Laser (1).pptxHajira Mahmood
24 views37 slides
Web Dev - 1 PPT.pdf by
Web Dev - 1 PPT.pdfWeb Dev - 1 PPT.pdf
Web Dev - 1 PPT.pdfgdsczhcet
60 views45 slides
Melek BEN MAHMOUD.pdf by
Melek BEN MAHMOUD.pdfMelek BEN MAHMOUD.pdf
Melek BEN MAHMOUD.pdfMelekBenMahmoud
14 views1 slide
handbook for web 3 adoption.pdf by
handbook for web 3 adoption.pdfhandbook for web 3 adoption.pdf
handbook for web 3 adoption.pdfLiveplex
22 views16 slides

Recently uploaded(20)

1st parposal presentation.pptx by i238212
1st parposal presentation.pptx1st parposal presentation.pptx
1st parposal presentation.pptx
i2382129 views
AMAZON PRODUCT RESEARCH.pdf by JerikkLaureta
AMAZON PRODUCT RESEARCH.pdfAMAZON PRODUCT RESEARCH.pdf
AMAZON PRODUCT RESEARCH.pdf
JerikkLaureta19 views
Web Dev - 1 PPT.pdf by gdsczhcet
Web Dev - 1 PPT.pdfWeb Dev - 1 PPT.pdf
Web Dev - 1 PPT.pdf
gdsczhcet60 views
handbook for web 3 adoption.pdf by Liveplex
handbook for web 3 adoption.pdfhandbook for web 3 adoption.pdf
handbook for web 3 adoption.pdf
Liveplex22 views
HTTP headers that make your website go faster - devs.gent November 2023 by Thijs Feryn
HTTP headers that make your website go faster - devs.gent November 2023HTTP headers that make your website go faster - devs.gent November 2023
HTTP headers that make your website go faster - devs.gent November 2023
Thijs Feryn21 views
Unit 1_Lecture 2_Physical Design of IoT.pdf by StephenTec
Unit 1_Lecture 2_Physical Design of IoT.pdfUnit 1_Lecture 2_Physical Design of IoT.pdf
Unit 1_Lecture 2_Physical Design of IoT.pdf
StephenTec12 views
Black and White Modern Science Presentation.pptx by maryamkhalid2916
Black and White Modern Science Presentation.pptxBlack and White Modern Science Presentation.pptx
Black and White Modern Science Presentation.pptx
maryamkhalid291616 views
DALI Basics Course 2023 by Ivory Egg
DALI Basics Course  2023DALI Basics Course  2023
DALI Basics Course 2023
Ivory Egg16 views
TouchLog: Finger Micro Gesture Recognition Using Photo-Reflective Sensors by sugiuralab
TouchLog: Finger Micro Gesture Recognition  Using Photo-Reflective SensorsTouchLog: Finger Micro Gesture Recognition  Using Photo-Reflective Sensors
TouchLog: Finger Micro Gesture Recognition Using Photo-Reflective Sensors
sugiuralab19 views
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N... by James Anderson
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...
James Anderson66 views
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas... by Bernd Ruecker
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
Bernd Ruecker33 views
Business Analyst Series 2023 - Week 3 Session 5 by DianaGray10
Business Analyst Series 2023 -  Week 3 Session 5Business Analyst Series 2023 -  Week 3 Session 5
Business Analyst Series 2023 - Week 3 Session 5
DianaGray10237 views
Lilypad @ Labweek, Istanbul, 2023.pdf by Ally339821
Lilypad @ Labweek, Istanbul, 2023.pdfLilypad @ Labweek, Istanbul, 2023.pdf
Lilypad @ Labweek, Istanbul, 2023.pdf
Ally3398219 views

RESTful modules in zf2

  • 1. RESTful Modules in ZF2 Walter Dal Mut – walter.dalmut@gmail.com - @walterdalmut https://github.com/wdalmut @walterdalmut - www.corley.it - www.upcloo.com
  • 2. About Me • Walter Dal Mut (@walterdalmut) • Electronic Engineer • Polytechnic University of Turin • Startupper • Corley S.r.l. – www.corley.it • Cloud Computing Services • UpCloo Ltd. – www.upcloo.com • Semantic Most Related Links service @walterdalmut - www.corley.it - www.upcloo.com
  • 3. Summary • REST introduction • REST constraints • Types of RESTful services • ZF2 RESTful modules • RESTful ZF2 URI tunneling module • RESTful ZF2 CRUD module @walterdalmut - www.corley.it - www.upcloo.com
  • 4. RESTful? What it means in few words… • Representational State Transfer (REST) • Architecture is based on Client-Server • Clients initiate requests to servers; servers process requests and return appropriate responses • Flexible, the application must know messages format • XML • JSON • Etc. @walterdalmut - www.corley.it - www.upcloo.com
  • 5. RESTful services are resource centric • Resources (sources of specific information) • Each resource is referenced with a global identifier (URI, etc.) • Any number of connectors can mediate the request • Clients • Servers • Caches • Tunnels @walterdalmut - www.corley.it - www.upcloo.com
  • 6. REST Constraints • Client-Server • A uniform interface separates clients from servers. • Stateless • The client–server communication is further constrained by no client context being stored on the server between requests. • Cacheable • Clients can cache responses • Layered System • Intermediary servers may improve system scalability by enabling load-balancing and by providing shared caches. They may also enforce security policies. • Uniform interface • Simplify and decouples the architecture @walterdalmut - www.corley.it - www.upcloo.com
  • 7. Several types of RESTful services • URI Templates • http://rest.domain.tld/order/{orderID} • One of the major uses for URI templates is as human- and machine-readable documentation. • URI Tunneling • http://rest.domain.tld/PlaceOrder?pizza=margherita&type=classic • Rest.domain.tld  service • PlaceOrder method • Pizza=margherita&type=classic  arguments • POX – Plain Old XML over HTTP • Similar to URI Tunneling but information will be sent as XML document in the HTTP request from the customer. @walterdalmut - www.corley.it - www.upcloo.com
  • 8. POX – Plain Old XML over HTTP example POST /PlaceOrder HTTP/1.1 Content-Type: application/xml Client application Application domain <Order> <Pizza> <Name>margherita</Name> <Type>classic</Type> </Pizza> </Order> HTTP/1.1 200 OK <OrderConfirmation> <OrderID>1345</OrderID> </OrderConfirmation> @walterdalmut - www.corley.it - www.upcloo.com
  • 9. CRUD Webservices • CRUD what it means? • Create, Read, Update and Delete • Patterns for manipulating resources across the network • Extended usage of HTTP verbs • GET • POST • PUT • DELETE • Using HTTP as an application protocol instead of a transport protocol • Web is really a big framework for building distributed systems. @walterdalmut - www.corley.it - www.upcloo.com
  • 10. HTTP verbs in CRUD services • Get Read Operation • Used to retrive resource details • http://rest.service.tld/order/10 • Post  Create Operation • Used to create new resources • Put Update Operation • Used to update existing resources • Delete Delete Operation • Used to delete existing resources POST/PUT can be exchanged and sometimes PUT/DELETE can be excluded to enable javascript integration (PUT/DELETE not supported browser side [HTTP_X_HTTP_METHOD_OVERRIDE parameter]) @walterdalmut - www.corley.it - www.upcloo.com
  • 11. CRUD Summary Verb URI or Template Use POST /order Create a new order, and upon success, receive a Location header specifying the new order’s URI. GET /order/{id} Request the current state of the order specified by the URI. PUT /order/{id} Update an order at the given URI with new information, providing the full representation. DELETE /order/{id} Logically remove the order identified by the given URI. @walterdalmut - www.corley.it - www.upcloo.com
  • 12. Status code definition (short list) • 2xx (Positives) • 200 OK – The request has succeeded. • 201 Created – The server accept the request and it has created the resource. • 202 Accepted – The request has been accepted for processing, but the processing has not been completed. • 4xx (Client Errors) • 400 Bad Request – The request could not be understood by the server due to malformed syntax. • 401 Unauthorized – The request requires user authentication. • 403 Forbidden – The server understood the request, but is refusing to fulfill it. • 404 Not found – The server has not found anything matching the Request-URI. • 405 Method not allowed – The method specified in the Request-Line is not allowed for the resource identified by the Request-URI. • 5xx (Server Errors) • 500 Internal Server Error – The server encountered an unexpected condition which prevented it from fulfilling the request. • 501 Not implemented – The server does not support the functionality required to fulfill the request. • 503 Service unavailable – The server is currently unable to handle the request due to a temporary overloading or maintenance of the server. @walterdalmut - www.corley.it - www.upcloo.com
  • 13. RESTful module idea • Router • Wire requests to RESTful controllers • RESTful Controllers requests Router • Uses HTTP verbs to call dedicated actions • Query models in order to serve RESTful responses Models • POST Processors Controllers • Create valid messages using formats • JSON Responses POST • XML Processor • Etc. @walterdalmut - www.corley.it - www.upcloo.com
  • 14. Realize ZF2 tunneling RESTful module • ZF1 provides «Zend_Rest_Server» that realize URI tunneling • We can realize the same thing in 2 minutes thanks to ZF2 flexibility. • We need to configure • Router • Events • A simple example here: • https://github.com/wdalmut/ZF2-Tunneling-Restful-Module-Skeleton @walterdalmut - www.corley.it - www.upcloo.com
  • 15. ZF2 URI Tunneling - Configuration <?php return array( We have created a simple base route «/tunnel» 'controllers' => array( 'invokables' => array( and a dynamic rule that select a «model» and an 'index' => 'TunnelingRestController', ) attached «action» ), 'router' => array( 'routes' => array( 'tunneling' => array( In simple words 'type' => 'ZendMvcRouterHttpSegment', 'options' => array( • http://my-app.local/tunnel/menu/get?id=1 'route' => '/tunnel', 'defaults' => array( • «menu» 'controller' => 'index', 'action' => 'index' • The model «TunnelingModelMenu» ), ), • «get» 'may_terminate' => true, 'child_routes' => array( • The model action «get()» 'default' => array( 'type' => 'ZendMvcRouterHttpSegment', • «id=1> 'options' => array( 'route' => '[/:model/:action]', • The action parameters «get(1)» 'constraints' => array( 'controller' => 'index', 'model' => '[a-zA-Z][a-zA-Z0-9_]*', 'action' => '[a-zA-Z][a-zA-Z0-9_]*' ), ), ), ), ), ), ) ); @walterdalmut - www.corley.it - www.upcloo.com
  • 16. ZF2 URI Tunneling - Controller <?php namespace TunnelingRest; The base «AbstractController» is very flexible Use … and enable us to use the «dispatch» action to class Controller extends AbstractController realize what we need in few lines. { public function onDispatch(MvcEvent $e) { $routeMatch = $e->getRouteMatch(); In practice we allocate the model and call the $params = $routeMatch->getParams(); $vars = get_object_vars($e->getRequest()->getQuery()); requested action. The return variable is used as $filter = new ZendFilterFilterChain(); response. $filter->attach(new ZendFilterWordDashToCamelCase()); $filter->attach(new ZendFilterCallback("lcfirst")); $action = $filter->filter($params["action"]); $filter->attach(new ZendFilterCallback("ucfirst")); In case of missing model or missing action an $model = $filter->filter($params["model"]); «InvalidArgumentException» is thrown. $classname = "TunnelingModel{$model}"; if (class_exists($classname)) { $clazz = new $classname; if (property_exists($clazz, $action)) { $ret = call_user_func_array(array($clazz, $action), $vars); $e->setResult($ret); return; } else { throw new InvalidArgumentException("Method "{$action}" doesn't exists'"); } } else { throw new InvalidArgumentException("Class "{$classname}" doesn't exists'"); } } } @walterdalmut - www.corley.it - www.upcloo.com
  • 17. ZF2 URI Tunneling – Model example <?php namespace TunnelingModel; As you can see, the «model» is a simple class definition. class Menu { public function get($id) { • /tunnel/menu/get?id=1 return array("id" => $id); } • /tunnel/menu/add?x=pizza&y=4 public function add($name, $value) { Very simple implementation return array("name" => $name, "value" => $value); } } @walterdalmut - www.corley.it - www.upcloo.com
  • 18. ZF2 URI Tunneling – JSON responses <?php namespace Tunneling; Thanks to events we can wire controller output use ZendMvcMvcEvent; to a post processor that converts responses in class Module json messages. { public function onBootstrap($e) { /** @var ZendModuleManagerModuleManager $moduleManager */ • Attach a «postProcess» action and create a $moduleManager = $e->getApplication()->getServiceManager()->get('modulemanager'); /** @var ZendEventManagerSharedEventManager $sharedEvents */ json message. $sharedEvents = $moduleManager->getEventManager()->getSharedManager(); $sharedEvents->attach( 'ZendMvcControllerAbstractController', MvcEvent::EVENT_DISPATCH, array($this, 'postProcess'), -100 ); } //… public function postProcess(MvcEvent $e) { $routeMatch = $e->getRouteMatch(); if (strpos($routeMatch->getMatchedRouteName(), "tunneling") !== false) { $e->getResponse()->setContent(json_encode($e->getResult()->getVariables())); return $e->getResponse(); } } } @walterdalmut - www.corley.it - www.upcloo.com
  • 19. ZF2 RESTful CRUD modules • ZF2 provides a base controller class that can help us to realize RESTful modules in few steps • ZendMvcControllerAbstractRestfulController • CRUD based implementation (Extended) • get($id) • delete($id) • update($id) • create($id) @walterdalmut - www.corley.it - www.upcloo.com
  • 20. ZF2 RESTful CRUD module example • Clone ZF2 Skeleton Application • Git clone https://github.com/zendframework/ZendSkeletonApplication.git my-app • Git submodule init • Git submodule update • Clone a ZF2 RESTful module • Git submodule add https://github.com/wdalmut/ZF2-Restful-Module-Skeleton.git module/Main • Add «Main» module into «configs/application.config.php» • Create you application virtual host and try it • http://my-app.local/rest/info/json [getList] • http://my-app.local/rest/info/json/1 [get] • curl –X POST –d ‘hello=world’ http://my-app.local/rest/info [create] • curl –X PUT –d ‘hello=ciao’ http://my-app.local/rest/info/1 [update] • curl –X DELETE http://my-app.local/rest/info/1 [delete] @walterdalmut - www.corley.it - www.upcloo.com
  • 21. RESTful Controllers <?php • RESTful Controller should extends AbstractRestfulController namespace MainController; • 5 abstract methods (CRUD + List) use ZendMvcControllerAbstractRestfulController; • getList class InfoController extends AbstractRestfulController { • GET operation without parameters public function getList() { • /rest/json/info } return array('ciao' => 'mondo'); • Get public function get($id) • READ resource with parameters (ID) { • /rest/json/info/1 } • Delete public function delete($id) { • DELETE a resource } • Update public function update($id, $data) • UPDATE a resource { • Create } • CREATE a new resource public function create($data = null) { } } @walterdalmut - www.corley.it - www.upcloo.com
  • 22. First of all play with routes 'router' => array( 'routes' => array( • Create a base route /rest that enable also formatters 'restful' => array( 'type' => 'ZendMvcRouterHttpSegment', • Formatter allow us to switch easly to JSON, 'options' => array( 'route' => '/rest[/:formatter]', XML etc. 'constraints' => array( • Child routes play with controller and identifiers 'formatter' => '[a-zA-Z0-9_-]*', ), ), 'may_terminate' => true, 'child_routes' => array( 'default' => array( 'type' => 'ZendMvcRouterHttpSegment', 'options' => array( 'route' => '[/:controller[/:id]]', 'constraints' => array( 'controller' => '[a-zA-Z][a-zA-Z0-9_-]*', 'id' => '[a-zA-Z0-9_-]*' ), ), ), ), ), ), @walterdalmut - www.corley.it - www.upcloo.com
  • 23. Formatters • RESTful services can handle different type of messages • JSON • XML • Images • Etc • The high modularity of ZF2 MVC implementation enable us to add different layers of abstractions and formatters is one of this. • Client must know what kind of messages type have to handle. • Post Processors are used to render messages @walterdalmut - www.corley.it - www.upcloo.com
  • 24. Formatters «configs/module.config.php» 'errors' => array( 'post_processor' => 'json-pp', • The configuration allows us to define different «post processors» 'show_exceptions' => array( 'message' => true, • Errors can be detailed more, for example traces, messages etc. 'trace' => true ) ), 'di' => array( 'instance' => array( 'alias' => array( 'json-pp' => 'MainPostProcessorJson', 'jsonp-pp' => 'MainPostProcessorJsonp', 'image-pp' => 'MainPostProcessorImage' ) ) ), @walterdalmut - www.corley.it - www.upcloo.com
  • 25. Wiring events (Module.php) /** * @param MvcEvent $e */ public function onBootstrap($e) • Event position -100 { /** @var ZendModuleManagerModuleManager $moduleManager */ • Handle post processors $moduleManager = $e->getApplication()->getServiceManager()->get('modulemanager'); /** @var ZendEventManagerSharedEventManager $sharedEvents */ • Event position 100 $sharedEvents = $moduleManager->getEventManager()->getSharedManager(); • Handle HTTP Method Override $sharedEvents->attach( • Event position 999 'ZendMvcControllerAbstractRestfulController', MvcEvent::EVENT_DISPATCH, • Handle errors array($this, 'postProcess'), -100 ); $sharedEvents->attach( 'MainControllerInfoController', MvcEvent::EVENT_DISPATCH, array($e->getApplication()->getServiceManager()->get('MainHttpRestful'), 'onDispatch'), 100 ); $sharedEvents->attach( 'ZendMvcApplication', MvcEvent::EVENT_DISPATCH_ERROR, array($this, 'errorProcess'), 999 ); } @walterdalmut - www.corley.it - www.upcloo.com
  • 26. Attach Post Processor to Actions public function postProcess(MvcEvent $e) { $routeMatch = $e->getRouteMatch(); $formatter = $routeMatch->getParam('formatter', false); $di = $e->getTarget()->getServiceLocator()->get('di'); if ($formatter !== false) { if ($e->getResult() instanceof ZendViewModelViewModel) { if (($e->getResult()->getVariables())) { $vars = $e->getResult()->getVariables(); } else { $vars = null; } } else { $vars = $e->getResult(); } $postProcessor = $di->get($formatter . '-pp', array( 'request' => $e->getRequest(), 'response' => $e->getResponse(), 'vars' => $vars, )); $postProcessor->process(); return $postProcessor->getResponse(); } return null; } @walterdalmut - www.corley.it - www.upcloo.com
  • 27. Example of JSON Post Processor <?php <?php namespace MainPostProcessor; namespace MainPostProcessor; /** abstract class AbstractPostProcessor * { */ protected $_vars = null; class Json extends AbstractPostProcessor private $_request = null; { private $_response = null; public function process() { public function __construct $result = json_encode($this->_vars); (ZendHttpRequest $request, ZendHttpResponse $response, $vars = null) { $headers = $this->getResponse()->getHeaders(); $this->_vars = $vars; $headers->addHeaderLine('Content-Type', 'application/json'); $this->_response = $response; $this->_request = $request; $this->getResponse()->setHeaders($headers); } $this->getResponse()->setContent($result); } public function getResponse() } { return $this->_response; } public function getRequest() { return $this->_request; } abstract public function process(); } @walterdalmut - www.corley.it - www.upcloo.com
  • 28. ZF2 RESTful Modules Thanks for listening… Any questions? @walterdalmut - www.corley.it - www.upcloo.com

Editor's Notes

  1. Ringrazione l’organizzazione dello ZFDAY, gli sponsor e tutte le persone presenti.
  2. Abbiamo solo 30 minuti quindi fare un veloce escursus sui service RESTful e vedremo come realizzare due moduli ZF2.Un primo molto semplice, ispirato a Zend_Rest_Server di ZF1 Un secondo utilizzando un componente integrato nella libreria ZF2
  3. Il termite REST è stato coniato nel 2000 da Roy Fielding, uno degli autori del protocollo HTTP, per descrivere un sistema che permette di descrivere ed identificare le risorse web.