SlideShare a Scribd company logo
Pick Your Protocol Creating Web Services with Zend Framework Matthew Turland September 17, 2008
Everyone acquainted? Lead Programmer for  surgiSYS, LLC ZCE, ZFCE, and Zend Framework contributor Blog:  http://ishouldbecoding.com
You're probably wondering... ... what you're doing here this early in the morning. Web services? Anyone? Anyone? According to the W3C , "a software system designed to support interoperable machine-to-machine interaction over a network." This by itself is vague. The remainder of the definition gets into specifics about SOAP, which is too exclusive.
What  are  web services? For our purposes, web applications implementing communication standards for receiving requests from other web applications to return or operate on data. Automate interactions between software systems that would otherwise require (more) human intervention. Scapegoat for the existence of a number of acronyms in today's IT industry. More on these shortly.
What is Zend Framework? Open source web application framework for PHP 5. Sponsored by Zend Technologies. Technology partners include IBM, Google, and Microsoft. Developed by Zend and volunteers since 2005. Great way to develop web services regardless of the implementation method you want to use.
What We're Covering Implementation of HTTP authentication to restrict access to web services. Background information on commonly used standards and methodologies for development of web services. Timely details on the state and use of Zend Framework components used to accelerate web service development.
HTTP Authentication Extension of the HTTP protocol used for identity authentication as described in  RFC 2617 . Sees limited use in access control implementations for web services and general web applications. Two flavors: Basic and Digest. The latter implements more measures for security than the former, but is less commonly used.
Zend_Auth_Adapter_Http Offers support for Basic and Digest authentication schemes and authentication via local and proxy servers. Some Digest features, such as nonce tracking for stale support, are not implemented yet. Uses resolvers to authenticate provided credentials against a data source. Uses a file-based resolver by default and offers an interface to implement custom resolvers.
File Resolver Formats Format is the same for both Basic and Digest schemes, but supplied data differs between schemes. Basic [$username]:[$realm]:[base64_encode($password)] Digest [$username]:[$realm]:[md5($username . ':' . $realm . ':' . $password)]
Configuration $basicResolver = new Zend_Auth_Adapter_Http_Resolver_File('path/to/file'); $adapter = new Zend_Auth_Adapter_Http(array( 'accept_schemes' => 'basic', 'realm' => '[Web Service Name]' )); $adapter // request and response are from controller ->setRequest($this->_request) ->setResponse($this->_response) ->setBasicResolver($basicResolver);
Use Case // Pulls authentication credentials from the request $result = $adapter->authenticate(); if (!$result->isValid()) { $errors = $result->getMessages(); } else { $identity = $result->getIdentity(); }
HTTP Resources RFC 2616 HyperText Transfer Protocol RFC 3986 Uniform Resource Identifiers "HTTP: The Definitive Guide" (ISBN 1565925092) "HTTP Pocket Reference: HyperText Transfer Protocol" (ISBN 1565928628) "HTTP Developer's Handbook" (ISBN 0672324547) by  Chris Shiflett Ben Ramsey's blog series on HTTP
Common Server Components Zend_Server_Interface "enforces" the use of the  SoapServer  API on server classes. Zend_Server_Reflection  extends the PHP 5  Reflection API  to add various features used in server introspection for delivering API metadata to clients. Zend_Server_Abstract is likely to be deprecated or significantly refactored in future releases.
Acronym #1 REST: REpresentational State Transfer Born in 2000 in the dissertation of Roy Fielding, a principal author of the HTTP specification. Not tied to a specific protocol, but most often implemented on an HTTP server. A collection of network architecture principles centered around resources and operations to facilitate transfer of state between clients and servers.
What's a resource? Source of specific information in a particular format (known as its representation). Platform-independent machine equivalent of a noun. Referred to using Universal Resource Identifiers or URIs.  A client can interact with a resource by knowing its URI, the operation to perform, and how to interpret the returned resource representation.
Operations HTTP POST GET PUT DELETE CRUD Create, Update, Delete Retrieve Create, Delete/Create Delete
Representations Anything with an associated MIME type. A single resource can have multiple representations. Content negotiation  allows the client to indicate what representations it supports and prefers. Some web services add a request parameter or  extension to the resource URI to indicate the requested representation. Not very RESTful, but easier to use.
Still don't get it? REST is not a standard, protocol, or architecture so much as an architectural style or set of design principles. Check out "RESTful Web Services" by Leonard Richardson and Sam Ruby, ISBN 0596529260. Keep listening, contrasts later on in this presentation may make the nature of REST more clear.
Zend_Rest_Server Exposes normal functions and class methods for remote invocation. Can return or directly output return values of the exposed functions and methods. Supports output of DOMNode, DOMDocument, and SimpleXMLElement return values. Non-XML return types are converted to XML using DOM.
Sound strange? Only HTTP methods supported are GET and POST, so it ends up being more like "REST-RPC" than REST. (Ben Ramsey has a  good blog post  on this.) XML output is assumed, which makes the class inflexible toward other representations (ex: JSON via  Zend_Json ). Very sparse documentation.
$server = new Zend_Rest_Server(); $server->addFunction('someFunctionName'); $server->addFunction('someOtherFunctionName'); $functions = $server->getFunctions(); $server->setClass( 'Some_Class_Name',  null, // namespace from Zend_Server_Interface $args // for Some_Class_Name::__construct() ); $server->handle($request); // $request = $_REQUEST $server->returnResponse(true); $return = $server->handle($request); Show me the code!
Don't bother with these... // They either are stubs or they may as well be. $server->setEncoding('UTF-8'); $encoding = $server->getEncoding(); $server->loadFunctions($functions); $server->setPersistence($mode); $headers = $server->getHeaders();
Alternative Approach Zend_Rest_Server  is likely to be on the chopping block in the 2.0 branch. Don't use it for new projects and make it a long-term goal to migrate existing projects using it. Use Zend Framework  MVC  features together with the  ContextSwitch  action helper to vary the returned resource representation. Keep an eye out for new developments to support REST services.
RESTful Routing Default routes in the rewrite router offer no standard conducive toward the REST approach. Zend_Controller_Router_Route_Rest  is a new (as in not-yet-approved) proposal by Luke Crouch to implement a common URI-to-action mapping for RESTful web services.
Zend_Rest_Client Lightweight wrapper for Zend_Http_Client geared toward consuming REST-based services. Can be used to implement automated test suites for application components that use Zend_Rest_Server. __call() implementation follows suit with the REST-RPC style of the server component. Using Zend_Http_Client itself is likely a better idea.
REST Demo Check my blog for slides and demo source code after the conference.
Acronym #2 XML-RPC: eXtensible Markup Language Remote Procedure Call Created by Dave Winer of UserLand Software in 1998 in conjunction with Microsoft. RPC model using XML as its data exchange format and HTTP as its data transport protocol. Intended to be a simple, minimalistic, and easy to use protocol.
What is XML? eXtensible Markup Language General-purpose spec for creating custom markup languages (ex:  XHTML ,  RSS ,  Atom ,  SVG ). Fee-free W3C-recommended open  standard . Primary purpose is to help information systems share structured data. <EverybodyStandBack /> I know XML
What is RPC? Remote Procedure Call Originated in 1976 in RFC 707. Also referred to as remote (method) invocation. General term for the ability of a computer program to  execute a subroutine in a remote address space. Popular paradigm for implementation of the client-server model of distributed computing using message passing.
REST versus RPC REST Nouns Principles Architecture Generally atomic RPC Verbs Standards Implementation Generally not
Zend_XmlRpc_Server Zend_XmlRpc_Server  is a full-featured XML-RPC server implementation of the specifications found at  http://xmlrpc.com . Natively supports procedure namespaces and implements expected system.* procedures internally using  Zend_Server_Reflection . Prevents output of information for exceptions not thrown by the server component using a whitelisting approach.
XML-RPC Components Zend_XmlRpc_Request and Zend_XmlRpc_Response  are data structures for client requests to servers and server responses to clients respectively. Zend_XmlRpc_Server allows for injection of custom  request  instances and use of custom  response  classes. Zend_XmlRpc_Server_Fault  manages whitelisting of exceptions that may be thrown during server operations, in order to ensure application security.
Boxcarring Requests Extension to the XML-RPC protocol that allows multiple procedure calls to be sent within a single server request. Not supported by all servers. Support is denoted by the presence of  system.multicall  in response to a call to  system.listMethods . Zend_XmlRpc_Server supports this feature.
Zend_XmlRpc_Server_Cache System.* methods support uses Zend_Server_Reflection to handle class introspection, which can be expensive. Zend_XmlRpc_Server_Cache  can be used to cache server definitions to a file for better performace. If get($cacheFilePath, $xmlRpcServerInstance) returns true, skip server configuration. Otherwise, configure your server class like normal and then call save($cacheFilePath, $xmlRpcServerInstance).
Zend_XmlRpc_Client Zend_XmlRpc_Client  supports consumption of remote XML-RPC services and unit testing of server implementations. Automatically handles type conversion between PHP and XML-RPC data types and allows for independent handling of both HTTP errors and XML-RPC faults. Natively supports introspection operations on servers that support the de facto system methods.
Zend_XmlRpc_Client_ServerProxy Zend_XmlRpc_Client_ServerProxy  proxies remote XML-RPC namespaces to allow them to function as native PHP objects. Ex:  $client->getProxy()-> system -> listMethods (); vs.  $client->call(' system . listMethods ');
XML-RPC Demo And now for something completely different: a demo that actually uses the server components I was just talking about!
Acronym #3 JSON-RPC: JavaScript Object Notation Remote Procedure Call RPC model similar to XML-RPC except that it uses using JSON as its data exchange format instead of XML. Designed for extreme ease of use. Current working draft  version is 1.1.  Specification proposal  for version 2.0 was released in March 2008.
What is JSON? JSON: JavaScript Object Notation Text-based human-readable data interchange format. Based on a subset of JavaScript, but considered to be a language-independent format. Detailed in  RFC 4627  by Douglas Crockford.
JSON versus XML Pros of JSON Extremely simple Lighter payload Native data type support Cons of JSON Fewer available supporting technologies No native support for binary data or namespaces Primitive data type support is weak Not extensible
Zend_Json_Server Supports versions 1 and 2 of the JSON-RPC specification found at  http://json-rpc.org . Zend_Json_Server_Smd  supports the  Service Mapping Description specification  for providing service metadata to clients. Interoperable with  Zend_Dojo_Data , the new data component for the Dojo toolkit in Zend Framework 1.6.
JSON-RPC Components Zend_Json_Server_Request  and  Zend_Json_Server_Response  are data structures for client requests to servers and server responses to clients respectively. Zend_Json_Server_Error  is a data structure for exceptions that may occur in processing requests. Zend_Json_Server  allows for injection of request and response instances.
Zend_Json_Client ... NOT! Poor Man's Zend_Json_Client Populate a Zend_Json_Server_Request instance with a method, parameters, and a request identifer. Send the return value of $request->toJson() to the service endpoint via an HTTP POST operation using Zend_Http_Client. Pass the HTTP response body to Zend_Json::decode() to get the equivalent PHP data structure.
JSON Demo This is the last one... after the next one, of course.
Acronym #4 SOAP (pre-1.2 - Simple Object Access Protocol) Protocol for exchanging XML-based messages. Originally designed by Dave Winer, Don Box, Bob Atkinson, and Mohsen Al-Ghosein in 1998, with backing from Microsoft, to be the successor of XML-RPC. Version 1.2  of the spec became a W3C recommendation in June 2003. Spec is currently maintained by the W3C  XML Protocol Working Group .
SOAP versus XML-RPC  SOAP message structure is more complex and syntax more verbose than XML-RPC because it allows for extensive message customization. SOAP supports user-defined data types (UDTs) while XML-RPC types are finite and predefined. SOAP supports enumerations, XML namespaces, XML Schemas, and other advanced features.
Zend_Soap_Server Intended purpose of  Zend_Soap_Server  is to simplify use and implementation of SOAP within PHP applications. API is compatible with the  SoapServer  component of the standard PHP SOAP extension. Composes it to add request, response, and service metadata handling. Same two modes of operation: WSDL and non-WSDL.
What is WSDL? Web Services Description Language XML-based language for describing how to access and use web services and the structure of their output. Not tied to SOAP, but often used with it. Version 2.0  (formerly 1.2) is a W3C recommendation and has better support for RESTful services, but is less widely adopted  than its predecessor version 1.1. Writing it is about as pleasant as getting a root canal.
Zend_Soap_Autodiscover Zend_Soap_Autodiscover  can generate WSDL from the source code of the class you expose as a SOAP service. It has a SoapServer-compatible API, but doesn't implement any logic for most methods. Instantiate within a controller, call setClass or addFunction, handle, done. Uses  Zend_Server_Reflection  to get class and type information,  Zend_Soap_Wsdl  for WSDL generation, and current request information for endpoint metadata.
Zend_Soap_Client Composes the SoapClient component of the standard PHP SOAP extension to add request and response handling and accessor and mutator methods for all configuration options. Includes methods that can be overridden in custom clients for preprocessing of arguments and service operation results. Useful for testing Zend_Soap_Server-based services.
SOAP Demo OK, this really is the last one this time. Really.
In conclusion... ... people who end their presentations with sentences starting with &quot;in conclusion&quot; have no creativity. Or are just inherently lazy. Or both. As in many arenas, there is no end-all be-all &quot;best&quot; choice of implementation. It's all about what your needs are and what tools can meet them. Zend Framework supports RAD development for the common methods of web service in today's marketplace.
Questions? No heckling... OK, maybe just a little. I will hang around afterward if you have questions, points for discussion, or just want to say hi. It's cool, I don't bite or have cooties or anything. I have business cards too. I work with Zend Framework on a fairly regular basis these days and generally blog about my experiences at  http://ishouldbecoding.com. </ShamelessPlug> Thanks for coming!

More Related Content

PPTX
An Introduction To REST API
PPTX
REST API Design & Development
PDF
REST API and CRUD
PDF
Restful api design
PDF
REST full API Design
PPTX
Demystify Salesforce Bulk API
PPSX
Rest api standards and best practices
PDF
REST-API overview / concepts
An Introduction To REST API
REST API Design & Development
REST API and CRUD
Restful api design
REST full API Design
Demystify Salesforce Bulk API
Rest api standards and best practices
REST-API overview / concepts

What's hot (20)

PDF
Rest api design by george reese
PPT
Introduction To REST
PPTX
Rest assured
PPTX
API Design- Best Practices
PPTX
REST-API introduction for developers
PPTX
What is an API?
PPT
Salesforce REST API
PDF
API Testing. Streamline your testing process.
PDF
Best Practices in Web Service Design
PDF
Guide on scaling web app
PDF
Api presentation
PPTX
Postman. From simple API test to end to end scenario
PPT
Introduction to the Web API
PPTX
LAJUG Napster REST API
PPT
Restful services with ColdFusion
PPTX
SFDC REST API
PPTX
Test in Rest. API testing with the help of Rest Assured.
PPTX
ASP.NET Web API and HTTP Fundamentals
PPTX
REST-API's for architects and managers
PPTX
REST & RESTful Web Services
Rest api design by george reese
Introduction To REST
Rest assured
API Design- Best Practices
REST-API introduction for developers
What is an API?
Salesforce REST API
API Testing. Streamline your testing process.
Best Practices in Web Service Design
Guide on scaling web app
Api presentation
Postman. From simple API test to end to end scenario
Introduction to the Web API
LAJUG Napster REST API
Restful services with ColdFusion
SFDC REST API
Test in Rest. API testing with the help of Rest Assured.
ASP.NET Web API and HTTP Fundamentals
REST-API's for architects and managers
REST & RESTful Web Services
Ad

Viewers also liked (7)

PDF
Introduction to Zend Framework web services
PDF
Criando aplicações RestFul com Zend Framework 2
PPT
Facebook Development with Zend Framework
PDF
Web services with laravel
PDF
Advanced Web Services Hacking (AusCERT 06)
PDF
Web Services PHP Tutorial
PDF
PHP and Web Services
Introduction to Zend Framework web services
Criando aplicações RestFul com Zend Framework 2
Facebook Development with Zend Framework
Web services with laravel
Advanced Web Services Hacking (AusCERT 06)
Web Services PHP Tutorial
PHP and Web Services
Ad

Similar to Creating Web Services with Zend Framework - Matthew Turland (20)

ODP
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
DOCX
Zend framework 2.0
PPTX
Creating web APIs with apigility
PDF
Web services tutorial
PDF
Web Services Tutorial
ODP
Web Scraping with PHP
PDF
PHP And Web Services: Perfect Partners
PDF
SOA with Zend Framework
PDF
Php and-web-services-24402
PPT
Demo
PPT
PPT
Greenathan
PPT
Greenathan
PPT
PPT
PPT
werwer
PPT
PPT
PPT
sdfsdf
PPT
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
Zend framework 2.0
Creating web APIs with apigility
Web services tutorial
Web Services Tutorial
Web Scraping with PHP
PHP And Web Services: Perfect Partners
SOA with Zend Framework
Php and-web-services-24402
Demo
Greenathan
Greenathan
werwer
sdfsdf

More from Matthew Turland (14)

PDF
New SPL Features in PHP 5.3
PDF
New SPL Features in PHP 5.3 (TEK-X)
PDF
PDF
Web Scraping with PHP
PPT
Web Scraping with PHP
PDF
Open Source Networking with Vyatta
PDF
When RSS Fails: Web Scraping with HTTP
PPT
Open Source Content Management Systems
ODP
PHP Basics for Designers
PPT
The OpenSolaris Operating System and Sun xVM VirtualBox - Blake Deville
ODP
Utilizing the Xen Hypervisor in business practice - Bryan Fusilier
PDF
The Ruby Programming Language - Ryan Farnell
ODP
PDQ Programming Languages plus an overview of Alice - Frank Ducrest
ODP
Getting Involved in Open Source - Matthew Turland
New SPL Features in PHP 5.3
New SPL Features in PHP 5.3 (TEK-X)
Web Scraping with PHP
Web Scraping with PHP
Open Source Networking with Vyatta
When RSS Fails: Web Scraping with HTTP
Open Source Content Management Systems
PHP Basics for Designers
The OpenSolaris Operating System and Sun xVM VirtualBox - Blake Deville
Utilizing the Xen Hypervisor in business practice - Bryan Fusilier
The Ruby Programming Language - Ryan Farnell
PDQ Programming Languages plus an overview of Alice - Frank Ducrest
Getting Involved in Open Source - Matthew Turland

Recently uploaded (20)

PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPT
Teaching material agriculture food technology
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
Spectroscopy.pptx food analysis technology
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
KodekX | Application Modernization Development
PDF
NewMind AI Weekly Chronicles - August'25 Week I
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
Cloud computing and distributed systems.
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
20250228 LYD VKU AI Blended-Learning.pptx
Teaching material agriculture food technology
Network Security Unit 5.pdf for BCA BBA.
sap open course for s4hana steps from ECC to s4
Programs and apps: productivity, graphics, security and other tools
Reach Out and Touch Someone: Haptics and Empathic Computing
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Unlocking AI with Model Context Protocol (MCP)
Per capita expenditure prediction using model stacking based on satellite ima...
Spectroscopy.pptx food analysis technology
Building Integrated photovoltaic BIPV_UPV.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
KodekX | Application Modernization Development
NewMind AI Weekly Chronicles - August'25 Week I
The AUB Centre for AI in Media Proposal.docx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
MYSQL Presentation for SQL database connectivity
Cloud computing and distributed systems.
How UI/UX Design Impacts User Retention in Mobile Apps.pdf

Creating Web Services with Zend Framework - Matthew Turland

  • 1. Pick Your Protocol Creating Web Services with Zend Framework Matthew Turland September 17, 2008
  • 2. Everyone acquainted? Lead Programmer for surgiSYS, LLC ZCE, ZFCE, and Zend Framework contributor Blog: http://ishouldbecoding.com
  • 3. You're probably wondering... ... what you're doing here this early in the morning. Web services? Anyone? Anyone? According to the W3C , &quot;a software system designed to support interoperable machine-to-machine interaction over a network.&quot; This by itself is vague. The remainder of the definition gets into specifics about SOAP, which is too exclusive.
  • 4. What are web services? For our purposes, web applications implementing communication standards for receiving requests from other web applications to return or operate on data. Automate interactions between software systems that would otherwise require (more) human intervention. Scapegoat for the existence of a number of acronyms in today's IT industry. More on these shortly.
  • 5. What is Zend Framework? Open source web application framework for PHP 5. Sponsored by Zend Technologies. Technology partners include IBM, Google, and Microsoft. Developed by Zend and volunteers since 2005. Great way to develop web services regardless of the implementation method you want to use.
  • 6. What We're Covering Implementation of HTTP authentication to restrict access to web services. Background information on commonly used standards and methodologies for development of web services. Timely details on the state and use of Zend Framework components used to accelerate web service development.
  • 7. HTTP Authentication Extension of the HTTP protocol used for identity authentication as described in RFC 2617 . Sees limited use in access control implementations for web services and general web applications. Two flavors: Basic and Digest. The latter implements more measures for security than the former, but is less commonly used.
  • 8. Zend_Auth_Adapter_Http Offers support for Basic and Digest authentication schemes and authentication via local and proxy servers. Some Digest features, such as nonce tracking for stale support, are not implemented yet. Uses resolvers to authenticate provided credentials against a data source. Uses a file-based resolver by default and offers an interface to implement custom resolvers.
  • 9. File Resolver Formats Format is the same for both Basic and Digest schemes, but supplied data differs between schemes. Basic [$username]:[$realm]:[base64_encode($password)] Digest [$username]:[$realm]:[md5($username . ':' . $realm . ':' . $password)]
  • 10. Configuration $basicResolver = new Zend_Auth_Adapter_Http_Resolver_File('path/to/file'); $adapter = new Zend_Auth_Adapter_Http(array( 'accept_schemes' => 'basic', 'realm' => '[Web Service Name]' )); $adapter // request and response are from controller ->setRequest($this->_request) ->setResponse($this->_response) ->setBasicResolver($basicResolver);
  • 11. Use Case // Pulls authentication credentials from the request $result = $adapter->authenticate(); if (!$result->isValid()) { $errors = $result->getMessages(); } else { $identity = $result->getIdentity(); }
  • 12. HTTP Resources RFC 2616 HyperText Transfer Protocol RFC 3986 Uniform Resource Identifiers &quot;HTTP: The Definitive Guide&quot; (ISBN 1565925092) &quot;HTTP Pocket Reference: HyperText Transfer Protocol&quot; (ISBN 1565928628) &quot;HTTP Developer's Handbook&quot; (ISBN 0672324547) by Chris Shiflett Ben Ramsey's blog series on HTTP
  • 13. Common Server Components Zend_Server_Interface &quot;enforces&quot; the use of the SoapServer API on server classes. Zend_Server_Reflection extends the PHP 5 Reflection API to add various features used in server introspection for delivering API metadata to clients. Zend_Server_Abstract is likely to be deprecated or significantly refactored in future releases.
  • 14. Acronym #1 REST: REpresentational State Transfer Born in 2000 in the dissertation of Roy Fielding, a principal author of the HTTP specification. Not tied to a specific protocol, but most often implemented on an HTTP server. A collection of network architecture principles centered around resources and operations to facilitate transfer of state between clients and servers.
  • 15. What's a resource? Source of specific information in a particular format (known as its representation). Platform-independent machine equivalent of a noun. Referred to using Universal Resource Identifiers or URIs. A client can interact with a resource by knowing its URI, the operation to perform, and how to interpret the returned resource representation.
  • 16. Operations HTTP POST GET PUT DELETE CRUD Create, Update, Delete Retrieve Create, Delete/Create Delete
  • 17. Representations Anything with an associated MIME type. A single resource can have multiple representations. Content negotiation allows the client to indicate what representations it supports and prefers. Some web services add a request parameter or extension to the resource URI to indicate the requested representation. Not very RESTful, but easier to use.
  • 18. Still don't get it? REST is not a standard, protocol, or architecture so much as an architectural style or set of design principles. Check out &quot;RESTful Web Services&quot; by Leonard Richardson and Sam Ruby, ISBN 0596529260. Keep listening, contrasts later on in this presentation may make the nature of REST more clear.
  • 19. Zend_Rest_Server Exposes normal functions and class methods for remote invocation. Can return or directly output return values of the exposed functions and methods. Supports output of DOMNode, DOMDocument, and SimpleXMLElement return values. Non-XML return types are converted to XML using DOM.
  • 20. Sound strange? Only HTTP methods supported are GET and POST, so it ends up being more like &quot;REST-RPC&quot; than REST. (Ben Ramsey has a good blog post on this.) XML output is assumed, which makes the class inflexible toward other representations (ex: JSON via Zend_Json ). Very sparse documentation.
  • 21. $server = new Zend_Rest_Server(); $server->addFunction('someFunctionName'); $server->addFunction('someOtherFunctionName'); $functions = $server->getFunctions(); $server->setClass( 'Some_Class_Name', null, // namespace from Zend_Server_Interface $args // for Some_Class_Name::__construct() ); $server->handle($request); // $request = $_REQUEST $server->returnResponse(true); $return = $server->handle($request); Show me the code!
  • 22. Don't bother with these... // They either are stubs or they may as well be. $server->setEncoding('UTF-8'); $encoding = $server->getEncoding(); $server->loadFunctions($functions); $server->setPersistence($mode); $headers = $server->getHeaders();
  • 23. Alternative Approach Zend_Rest_Server is likely to be on the chopping block in the 2.0 branch. Don't use it for new projects and make it a long-term goal to migrate existing projects using it. Use Zend Framework MVC features together with the ContextSwitch action helper to vary the returned resource representation. Keep an eye out for new developments to support REST services.
  • 24. RESTful Routing Default routes in the rewrite router offer no standard conducive toward the REST approach. Zend_Controller_Router_Route_Rest is a new (as in not-yet-approved) proposal by Luke Crouch to implement a common URI-to-action mapping for RESTful web services.
  • 25. Zend_Rest_Client Lightweight wrapper for Zend_Http_Client geared toward consuming REST-based services. Can be used to implement automated test suites for application components that use Zend_Rest_Server. __call() implementation follows suit with the REST-RPC style of the server component. Using Zend_Http_Client itself is likely a better idea.
  • 26. REST Demo Check my blog for slides and demo source code after the conference.
  • 27. Acronym #2 XML-RPC: eXtensible Markup Language Remote Procedure Call Created by Dave Winer of UserLand Software in 1998 in conjunction with Microsoft. RPC model using XML as its data exchange format and HTTP as its data transport protocol. Intended to be a simple, minimalistic, and easy to use protocol.
  • 28. What is XML? eXtensible Markup Language General-purpose spec for creating custom markup languages (ex: XHTML , RSS , Atom , SVG ). Fee-free W3C-recommended open standard . Primary purpose is to help information systems share structured data. <EverybodyStandBack /> I know XML
  • 29. What is RPC? Remote Procedure Call Originated in 1976 in RFC 707. Also referred to as remote (method) invocation. General term for the ability of a computer program to execute a subroutine in a remote address space. Popular paradigm for implementation of the client-server model of distributed computing using message passing.
  • 30. REST versus RPC REST Nouns Principles Architecture Generally atomic RPC Verbs Standards Implementation Generally not
  • 31. Zend_XmlRpc_Server Zend_XmlRpc_Server is a full-featured XML-RPC server implementation of the specifications found at http://xmlrpc.com . Natively supports procedure namespaces and implements expected system.* procedures internally using Zend_Server_Reflection . Prevents output of information for exceptions not thrown by the server component using a whitelisting approach.
  • 32. XML-RPC Components Zend_XmlRpc_Request and Zend_XmlRpc_Response are data structures for client requests to servers and server responses to clients respectively. Zend_XmlRpc_Server allows for injection of custom request instances and use of custom response classes. Zend_XmlRpc_Server_Fault manages whitelisting of exceptions that may be thrown during server operations, in order to ensure application security.
  • 33. Boxcarring Requests Extension to the XML-RPC protocol that allows multiple procedure calls to be sent within a single server request. Not supported by all servers. Support is denoted by the presence of system.multicall in response to a call to system.listMethods . Zend_XmlRpc_Server supports this feature.
  • 34. Zend_XmlRpc_Server_Cache System.* methods support uses Zend_Server_Reflection to handle class introspection, which can be expensive. Zend_XmlRpc_Server_Cache can be used to cache server definitions to a file for better performace. If get($cacheFilePath, $xmlRpcServerInstance) returns true, skip server configuration. Otherwise, configure your server class like normal and then call save($cacheFilePath, $xmlRpcServerInstance).
  • 35. Zend_XmlRpc_Client Zend_XmlRpc_Client supports consumption of remote XML-RPC services and unit testing of server implementations. Automatically handles type conversion between PHP and XML-RPC data types and allows for independent handling of both HTTP errors and XML-RPC faults. Natively supports introspection operations on servers that support the de facto system methods.
  • 36. Zend_XmlRpc_Client_ServerProxy Zend_XmlRpc_Client_ServerProxy proxies remote XML-RPC namespaces to allow them to function as native PHP objects. Ex: $client->getProxy()-> system -> listMethods (); vs. $client->call(' system . listMethods ');
  • 37. XML-RPC Demo And now for something completely different: a demo that actually uses the server components I was just talking about!
  • 38. Acronym #3 JSON-RPC: JavaScript Object Notation Remote Procedure Call RPC model similar to XML-RPC except that it uses using JSON as its data exchange format instead of XML. Designed for extreme ease of use. Current working draft version is 1.1. Specification proposal for version 2.0 was released in March 2008.
  • 39. What is JSON? JSON: JavaScript Object Notation Text-based human-readable data interchange format. Based on a subset of JavaScript, but considered to be a language-independent format. Detailed in RFC 4627 by Douglas Crockford.
  • 40. JSON versus XML Pros of JSON Extremely simple Lighter payload Native data type support Cons of JSON Fewer available supporting technologies No native support for binary data or namespaces Primitive data type support is weak Not extensible
  • 41. Zend_Json_Server Supports versions 1 and 2 of the JSON-RPC specification found at http://json-rpc.org . Zend_Json_Server_Smd supports the Service Mapping Description specification for providing service metadata to clients. Interoperable with Zend_Dojo_Data , the new data component for the Dojo toolkit in Zend Framework 1.6.
  • 42. JSON-RPC Components Zend_Json_Server_Request and Zend_Json_Server_Response are data structures for client requests to servers and server responses to clients respectively. Zend_Json_Server_Error is a data structure for exceptions that may occur in processing requests. Zend_Json_Server allows for injection of request and response instances.
  • 43. Zend_Json_Client ... NOT! Poor Man's Zend_Json_Client Populate a Zend_Json_Server_Request instance with a method, parameters, and a request identifer. Send the return value of $request->toJson() to the service endpoint via an HTTP POST operation using Zend_Http_Client. Pass the HTTP response body to Zend_Json::decode() to get the equivalent PHP data structure.
  • 44. JSON Demo This is the last one... after the next one, of course.
  • 45. Acronym #4 SOAP (pre-1.2 - Simple Object Access Protocol) Protocol for exchanging XML-based messages. Originally designed by Dave Winer, Don Box, Bob Atkinson, and Mohsen Al-Ghosein in 1998, with backing from Microsoft, to be the successor of XML-RPC. Version 1.2 of the spec became a W3C recommendation in June 2003. Spec is currently maintained by the W3C XML Protocol Working Group .
  • 46. SOAP versus XML-RPC SOAP message structure is more complex and syntax more verbose than XML-RPC because it allows for extensive message customization. SOAP supports user-defined data types (UDTs) while XML-RPC types are finite and predefined. SOAP supports enumerations, XML namespaces, XML Schemas, and other advanced features.
  • 47. Zend_Soap_Server Intended purpose of Zend_Soap_Server is to simplify use and implementation of SOAP within PHP applications. API is compatible with the SoapServer component of the standard PHP SOAP extension. Composes it to add request, response, and service metadata handling. Same two modes of operation: WSDL and non-WSDL.
  • 48. What is WSDL? Web Services Description Language XML-based language for describing how to access and use web services and the structure of their output. Not tied to SOAP, but often used with it. Version 2.0 (formerly 1.2) is a W3C recommendation and has better support for RESTful services, but is less widely adopted than its predecessor version 1.1. Writing it is about as pleasant as getting a root canal.
  • 49. Zend_Soap_Autodiscover Zend_Soap_Autodiscover can generate WSDL from the source code of the class you expose as a SOAP service. It has a SoapServer-compatible API, but doesn't implement any logic for most methods. Instantiate within a controller, call setClass or addFunction, handle, done. Uses Zend_Server_Reflection to get class and type information, Zend_Soap_Wsdl for WSDL generation, and current request information for endpoint metadata.
  • 50. Zend_Soap_Client Composes the SoapClient component of the standard PHP SOAP extension to add request and response handling and accessor and mutator methods for all configuration options. Includes methods that can be overridden in custom clients for preprocessing of arguments and service operation results. Useful for testing Zend_Soap_Server-based services.
  • 51. SOAP Demo OK, this really is the last one this time. Really.
  • 52. In conclusion... ... people who end their presentations with sentences starting with &quot;in conclusion&quot; have no creativity. Or are just inherently lazy. Or both. As in many arenas, there is no end-all be-all &quot;best&quot; choice of implementation. It's all about what your needs are and what tools can meet them. Zend Framework supports RAD development for the common methods of web service in today's marketplace.
  • 53. Questions? No heckling... OK, maybe just a little. I will hang around afterward if you have questions, points for discussion, or just want to say hi. It's cool, I don't bite or have cooties or anything. I have business cards too. I work with Zend Framework on a fairly regular basis these days and generally blog about my experiences at http://ishouldbecoding.com. </ShamelessPlug> Thanks for coming!