Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Creating Web Services with Zend Framework - Matthew Turland


Published on

Published in: Technology, Education

Creating Web Services with Zend Framework - Matthew Turland

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