SlideShare una empresa de Scribd logo
1 de 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

Más contenido relacionado

La actualidad más candente

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 JerseyStormpath
 
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.Mario Cardinal
 
RESTful API Automation with JavaScript
RESTful API Automation with JavaScriptRESTful API Automation with JavaScript
RESTful API Automation with JavaScriptJonathan LeBlanc
 
Understanding and testing restful web services
Understanding and testing restful web servicesUnderstanding and testing restful web services
Understanding and testing restful web servicesmwinteringham
 
Restful api design
Restful api designRestful api design
Restful api designMizan Riqzia
 
RESTful services
RESTful servicesRESTful services
RESTful servicesgouthamrv
 
Elegant Rest Design Webinar
Elegant Rest Design WebinarElegant Rest Design Webinar
Elegant Rest Design WebinarStormpath
 
Rest & RESTful WebServices
Rest & RESTful WebServicesRest & RESTful WebServices
Rest & RESTful WebServicesPrateek Tandon
 
Learn REST in 18 Slides
Learn REST in 18 SlidesLearn REST in 18 Slides
Learn REST in 18 SlidesSuraj Gupta
 
Pentesting RESTful webservices
Pentesting RESTful webservicesPentesting RESTful webservices
Pentesting RESTful webservicesMohammed A. Imran
 
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 CoreStormpath
 
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 ReSTBruno Kessler Foundation
 
Testing REST Web Services
Testing REST Web ServicesTesting REST Web Services
Testing REST Web ServicesJan Algermissen
 
REST-API introduction for developers
REST-API introduction for developersREST-API introduction for developers
REST-API introduction for developersPatrick Savalle
 
Best Practice in Web Service Design
Best Practice in Web Service DesignBest Practice in Web Service Design
Best Practice in Web Service DesignLorna Mitchell
 
Do not automate GUI testing
Do not automate GUI testingDo not automate GUI testing
Do not automate GUI testingAtila Inovecký
 

La actualidad más candente (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
 

Similar a RESTful modules in zf2

Solr Powered Lucene
Solr Powered LuceneSolr Powered Lucene
Solr Powered LuceneErik Hatcher
 
Rest presentation
Rest  presentationRest  presentation
Rest presentationsrividhyau
 
Apache Solr crash course
Apache Solr crash courseApache Solr crash course
Apache Solr crash courseTommaso Teofili
 
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 Ram Awadh Prasad, PMP
 
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 v2Christian Posta
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postvamsitricks
 
REST Methodologies
REST MethodologiesREST Methodologies
REST Methodologiesjrodbx
 
Meetup on Apache Zookeeper
Meetup on Apache ZookeeperMeetup on Apache Zookeeper
Meetup on Apache ZookeeperAnshul Patel
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postvamsi krishna
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postvamsitricks
 
Global Scale ESB with Mule
Global Scale ESB with MuleGlobal Scale ESB with Mule
Global Scale ESB with MuleAndrew Kennedy
 
Web Technologies in Java EE 7
Web Technologies in Java EE 7Web Technologies in Java EE 7
Web Technologies in Java EE 7Lukáš Fryč
 
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💡 Tomasz Kogut
 
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" DataArt
 

Similar a 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"
 

Más de Corley S.r.l.

Aws rekognition - riconoscimento facciale
Aws rekognition  - riconoscimento faccialeAws rekognition  - riconoscimento facciale
Aws rekognition - riconoscimento faccialeCorley S.r.l.
 
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 servicesCorley S.r.l.
 
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 awsCorley S.r.l.
 
AWSome day 2018 - database in cloud
AWSome day 2018 -  database in cloudAWSome day 2018 -  database in cloud
AWSome day 2018 - database in cloudCorley 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
Trace your micro-services oriented application with Zipkin and OpenTracing Corley S.r.l.
 
Apiconf - The perfect REST solution
Apiconf - The perfect REST solutionApiconf - The perfect REST solution
Apiconf - The perfect REST solutionCorley S.r.l.
 
Apiconf - Doc Driven Development
Apiconf - Doc Driven DevelopmentApiconf - Doc Driven Development
Apiconf - Doc Driven DevelopmentCorley S.r.l.
 
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 infrastructuresCorley S.r.l.
 
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 infrastructuresCorley S.r.l.
 
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 applicationCorley 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...
A single language for backend and frontend from AngularJS to cloud with Clau...Corley S.r.l.
 
AngularJS: Service, factory & provider
AngularJS: Service, factory & providerAngularJS: Service, factory & provider
AngularJS: Service, factory & providerCorley S.r.l.
 
The advantage of developing with TypeScript
The advantage of developing with TypeScript The advantage of developing with TypeScript
The advantage of developing with TypeScript Corley S.r.l.
 
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 deployCorley S.r.l.
 
Corley cloud angular in cloud
Corley cloud   angular in cloudCorley cloud   angular in cloud
Corley cloud angular in cloudCorley S.r.l.
 
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 Symfony2Corley S.r.l.
 
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 LambdaCorley 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...
Deploy and Scale your PHP App with AWS ElasticBeanstalk and Docker- PHPTour L...Corley S.r.l.
 
Middleware PHP - A simple micro-framework
Middleware PHP - A simple micro-frameworkMiddleware PHP - A simple micro-framework
Middleware PHP - A simple micro-frameworkCorley S.r.l.
 

Más de 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
 

Último

Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 

Último (20)

E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 

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

Notas del editor

  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.