SlideShare ist ein Scribd-Unternehmen logo
1 von 28
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

Weitere ähnliche Inhalte

Was ist angesagt?

RESTful services
RESTful servicesRESTful services
RESTful services
gouthamrv
 
Testing REST Web Services
Testing REST Web ServicesTesting REST Web Services
Testing REST Web Services
Jan Algermissen
 

Was ist angesagt? (19)

REST API Design for JAX-RS And Jersey
REST API Design for JAX-RS And JerseyREST API Design for JAX-RS And Jersey
REST API Design for JAX-RS And Jersey
 
Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.
 
RESTful API Automation with JavaScript
RESTful API Automation with JavaScriptRESTful API Automation with JavaScript
RESTful API Automation with JavaScript
 
Understanding and testing restful web services
Understanding and testing restful web servicesUnderstanding and testing restful web services
Understanding and testing restful web services
 
Restful api design
Restful api designRestful api design
Restful api design
 
RESTful services
RESTful servicesRESTful services
RESTful services
 
Elegant Rest Design Webinar
Elegant Rest Design WebinarElegant Rest Design Webinar
Elegant Rest Design Webinar
 
Rest & RESTful WebServices
Rest & RESTful WebServicesRest & RESTful WebServices
Rest & RESTful WebServices
 
Learn REST in 18 Slides
Learn REST in 18 SlidesLearn REST in 18 Slides
Learn REST in 18 Slides
 
Pentesting RESTful webservices
Pentesting RESTful webservicesPentesting RESTful webservices
Pentesting RESTful webservices
 
Building Beautiful REST APIs with ASP.NET Core
Building Beautiful REST APIs with ASP.NET CoreBuilding Beautiful REST APIs with ASP.NET Core
Building Beautiful REST APIs with ASP.NET Core
 
The Internet as Web Services: introduction to ReST
The Internet as Web Services: introduction to ReSTThe Internet as Web Services: introduction to ReST
The Internet as Web Services: introduction to ReST
 
Restful webservices
Restful webservicesRestful webservices
Restful webservices
 
Web API Basics
Web API BasicsWeb API Basics
Web API Basics
 
Testing REST Web Services
Testing REST Web ServicesTesting REST Web Services
Testing REST Web Services
 
REST APIs
REST APIsREST APIs
REST APIs
 
REST-API introduction for developers
REST-API introduction for developersREST-API introduction for developers
REST-API introduction for developers
 
Best Practice in Web Service Design
Best Practice in Web Service DesignBest Practice in Web Service Design
Best Practice in Web Service Design
 
Do not automate GUI testing
Do not automate GUI testingDo not automate GUI testing
Do not automate GUI testing
 

Ähnlich wie RESTful modules in zf2

Rest presentation
Rest  presentationRest  presentation
Rest presentation
srividhyau
 
Apache Solr crash course
Apache Solr crash courseApache Solr crash course
Apache Solr crash course
Tommaso Teofili
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
vamsitricks
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
vamsi krishna
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
vamsitricks
 
Web Technologies in Java EE 7
Web Technologies in Java EE 7Web Technologies in Java EE 7
Web Technologies in Java EE 7
Lukáš Fryč
 

Ähnlich wie RESTful modules in zf2 (20)

BeJUG JAX-RS Event
BeJUG JAX-RS EventBeJUG JAX-RS Event
BeJUG JAX-RS Event
 
Solr Powered Lucene
Solr Powered LuceneSolr Powered Lucene
Solr Powered Lucene
 
Rest presentation
Rest  presentationRest  presentation
Rest presentation
 
Apache Solr crash course
Apache Solr crash courseApache Solr crash course
Apache Solr crash course
 
An Overview of Web Services: SOAP and REST
An Overview of Web Services: SOAP and REST An Overview of Web Services: SOAP and REST
An Overview of Web Services: SOAP and REST
 
On being RESTful
On being RESTfulOn being RESTful
On being RESTful
 
ReST
ReSTReST
ReST
 
Microservices with Apache Camel, Docker and Fabric8 v2
Microservices with Apache Camel, Docker and Fabric8 v2Microservices with Apache Camel, Docker and Fabric8 v2
Microservices with Apache Camel, Docker and Fabric8 v2
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
REST Methodologies
REST MethodologiesREST Methodologies
REST Methodologies
 
Meetup on Apache Zookeeper
Meetup on Apache ZookeeperMeetup on Apache Zookeeper
Meetup on Apache Zookeeper
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
Global Scale ESB with Mule
Global Scale ESB with MuleGlobal Scale ESB with Mule
Global Scale ESB with Mule
 
Web Technologies in Java EE 7
Web Technologies in Java EE 7Web Technologies in Java EE 7
Web Technologies in Java EE 7
 
Exploring Twitter's Finagle technology stack for microservices
Exploring Twitter's Finagle technology stack for microservicesExploring Twitter's Finagle technology stack for microservices
Exploring Twitter's Finagle technology stack for microservices
 
Solr
SolrSolr
Solr
 
Windows 8 Metro apps and the outside world
Windows 8 Metro apps and the outside worldWindows 8 Metro apps and the outside world
Windows 8 Metro apps and the outside world
 
Servlets
ServletsServlets
Servlets
 
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"
IT talk SPb "Full text search for lazy guys"
 

Mehr von Corley S.r.l.

Mehr von Corley S.r.l. (20)

Aws rekognition - riconoscimento facciale
Aws rekognition  - riconoscimento faccialeAws rekognition  - riconoscimento facciale
Aws rekognition - riconoscimento facciale
 
AWSome day 2018 - scalability and cost optimization with container services
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
 
AWSome day 2018 - API serverless with aws
AWSome day 2018  - API serverless with awsAWSome day 2018  - API serverless with aws
AWSome day 2018 - API serverless with aws
 
AWSome day 2018 - database in cloud
AWSome day 2018 -  database in cloudAWSome day 2018 -  database in cloud
AWSome day 2018 - database in cloud
 
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
Trace your micro-services oriented application with Zipkin and OpenTracing
 
Apiconf - The perfect REST solution
Apiconf - The perfect REST solutionApiconf - The perfect REST solution
Apiconf - The perfect REST solution
 
Apiconf - Doc Driven Development
Apiconf - Doc Driven DevelopmentApiconf - Doc Driven Development
Apiconf - Doc Driven Development
 
Authentication and authorization in res tful infrastructures
Authentication and authorization in res tful infrastructuresAuthentication and authorization in res tful infrastructures
Authentication and authorization in res tful infrastructures
 
Flexibility and scalability of costs in serverless infrastructures
Flexibility and scalability of costs in serverless infrastructuresFlexibility and scalability of costs in serverless infrastructures
Flexibility and scalability of costs in serverless infrastructures
 
CloudConf2017 - Deploy, Scale & Coordinate a microservice oriented application
CloudConf2017 - Deploy, Scale & Coordinate a microservice oriented applicationCloudConf2017 - Deploy, Scale & Coordinate a microservice oriented application
CloudConf2017 - Deploy, Scale & Coordinate a microservice oriented application
 
React vs Angular2
React vs Angular2React vs Angular2
React vs Angular2
 
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...
A single language for backend and frontend from AngularJS to cloud with Clau...
 
AngularJS: Service, factory & provider
AngularJS: Service, factory & providerAngularJS: Service, factory & provider
AngularJS: Service, factory & provider
 
The advantage of developing with TypeScript
The advantage of developing with TypeScript The advantage of developing with TypeScript
The advantage of developing with TypeScript
 
Angular coding: from project management to web and mobile deploy
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 cloud angular in cloud
Corley cloud   angular in cloudCorley cloud   angular in cloud
Corley cloud angular in cloud
 
Measure your app internals with InfluxDB and Symfony2
Measure your app internals with InfluxDB and Symfony2Measure your app internals with InfluxDB and Symfony2
Measure your app internals with InfluxDB and Symfony2
 
Read Twitter Stream and Tweet back pictures with Raspberry Pi & AWS Lambda
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
 
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...
Deploy and Scale your PHP App with AWS ElasticBeanstalk and Docker- PHPTour L...
 
Middleware PHP - A simple micro-framework
Middleware PHP - A simple micro-frameworkMiddleware PHP - A simple micro-framework
Middleware PHP - A simple micro-framework
 

Kürzlich hochgeladen

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Kürzlich hochgeladen (20)

Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 

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

Hinweis der Redaktion

  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.