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.

Psr-7

1,184 views

Published on

A presentation on PSR-7, the proposed set of interfaces for HTTP messages in PHP

Published in: Software
  • Be the first to comment

Psr-7

  1. 1. PSR-7 A SET OF COMMON INTERFACES FOR HTTP MESSAGES by Marco Perone / @marcoshuttle
  2. 2. HTTP MESSAGES
  3. 3. HTTP MESSAGE STRUCTURE     <message line>     Header: value     Another­Header: value     Message body
  4. 4. BODY string handled by server and clients as a stream PHP natively represents it using streams
  5. 5. REQUEST MESSAGE LINE METHOD REQUEST-TARGET HTTP/VERSION
  6. 6. REQUEST TARGET origin form absolute form authority form asterisk form
  7. 7. URI SCHEME://AUTHORITY[/PATH][?QUERY STRING] AUTHORITY = [USER[:PASS]@]HOST[:PORT]
  8. 8. RESPONSE MESSAGE LINE HTTP/VERSION STATUS REASON
  9. 9. USE OF HTTP MESSAGES IN PHP
  10. 10. USE CASE 1 USE PHP SUPERGLOBALS Any application before frameworks
  11. 11. USE CASE 2 CREATE NEW IMPLEMENTATION FROM SCRATCH Frameworks define http components Single purpose libraries (oauth-server-php) Http clients ad Guzzle and Buzz
  12. 12. USE CASE 3 REQUIRE A SPECIFIC HTTP CLIENT/SERVER LIBRARY PROVIDING MESSAGE IMPLEMENTATION Silex, Stack, Drupal 8 have hard dependencies on Symfony's HTTP kernel Any SDK developed with Guzzle has a hard requirement on Guzzle's HTTP message implementations
  13. 13. USE CASE 4 CREATE ADAPTERS FOR COMMON HTTP MESSAGE IMPLEMENTATIONS Projects such as Geocoder create redundant adapters for common libraries
  14. 14. PROBLEMS Superglobals are mutable. Libraries can alter state of the application Unit and integration testing difficult Projects not capable of interoperability or cross- pollination Necessity of building a bridge layer between applications Any content emitted before a call to header()will result in that a call becoming a no-op
  15. 15. THE SCOPE OF PSR-7
  16. 16. GOALS Provide the interfaces needed for describing HTTP messages Focus on practical applications and usability Define the interfaces to model all elements of the HTTP message and URI specifications Ensure that the API does not impose arbitrary limits on HTTP messages Provide useful abstractions both for handling incoming requests for server-side applications and for sending outgoing requests in HTTP clients
  17. 17. NON GOALS Does not expect all HTTP client libraries or server-side frameworks to change their interfaces to conform. It is strictly meant for interoperability Should not impose implementation details
  18. 18. USE CASES
  19. 19. CLIENTS Unified message interface to use for making requests $response = $client­>send($request);                         
  20. 20. MIDDLEWARES Function that accepts request and response as parameters and does something with them, including delegating to the next middleware function (     ServerRequestInterface $request,     ResponseInterface $response,     callable $next = null ) {     # do stuff here }                         
  21. 21. FRAMEWORKS They did HTTP message abstraction since a long time PSR-7 provides a common set of interfaces Consider ZendStdlibDispatchableInterfacein Zend Framework 2 use ZendHttpRequestInterface; use ZendHttpResponseInterface; interface DispatchableInterface {     public function dispatch(         RequestInterface $request,         ResponseInterface $response     ); }                         
  22. 22. PSR-7 BY EXAMPLES
  23. 23. INTERMEZZO: VALUE OBJECTS Messages and URIs are modeled as value objects a change to any aspect of the message is essentially a new message immutability ensure integrity of message state use a base instance as prototype
  24. 24. MESSAGES namespace PsrHttpMessage; MessageInterface ResponseInterface RequestInterface ServerRequestInterface
  25. 25. HEADERS // Returns null if not found: $header = $message­>getHeader('Accept'); // Test for a header: if (! $message­>hasHeader('Accept')) { } // If the header has multiple values, fetch them // as an array: $values = $message­>getHeaderLines('X­Foo');                             
  26. 26. HEADERS /* Returns the following structure:     [         'Header' => [             'value1'             'value2'         ]     ] */ foreach ($message­>getAllHeaders() as $header => $values) { }                             
  27. 27. HEADERS $new = $message­>withHeader('Location', 'http://example.com'); $message = $message­>withHeader('Location', 'http://example.com'); $message = $message­>withAddedHeader('X­Foo', 'bar'); $message = $message­>withoutHeader('X­Foo');                             
  28. 28. BODIES treated as streams StreamableInterfaceis used $body = new Stream('php://temp'); $body­>write('Here is the content for my message!'); $message = $message­>withBody(new Stream('php://temp'));                         
  29. 29. RESPONSES status code reason phrase $status = $response­>getStatusCode(); $reason = $response­>getReasonPhrase(); $response = $response­>withStatus(418, "I'm a teapot");                         
  30. 30. REQUESTS method request target
  31. 31. REQUEST TARGET AND URI The request interface: composes a UriInterfaceinstance, which models the URI itself provides two methods around request-targets: getRequestTarget()and withRequestTarget()
  32. 32. URI INTERFACE URI are treated as value objects     // URI parts:     $scheme    = $uri­>getScheme();     $userInfo  = $uri­>getUserInfo();     $host      = $uri­>getHost();     $port      = $uri­>getPort();     $path      = $uri­>getPath();     $query     = $uri­>getQuery();     // the query STRING     $authority = $uri­>getAuthority(); // [user­info@]host[:port]     $uri = $uri         ­>withScheme('http')         ­>withHost('example.com')         ­>withPath('/foo/bar')         ­>withQuery('?baz=bat');                             
  33. 33. CREATE REQUEST     $request = $request         ­>withMethod('OPTION')         ­>withUri($uri­>withPath('/api/user'))         ­>withRequestTarget('*');                             
  34. 34. SERVER SIDE REQUESTS PHP's Server API does a number of things for us: Deserialization of query string arguments ($_GET) Deserialization of urlencoded form data submitted via POST ($_POST) Deserialization of cookies ($_COOKIE) Identification and handling of file uploads ($_FILES) Encapsulation of CGI/SAPI parameters ($_SERVER)
  35. 35. SERVER SIDE REQUESTS ServerRequestInterfaceextends the base RequestInterfaceand offers features around these values $query   = $request­>getQueryParams(); $body    = $request­>getParsedBody(); $cookies = $request­>getCookieParams(); $files   = $request­>getFileParams(); $server  = $request­>getServerParams();                             
  36. 36. ATTRIBUTES $request­>getAttribute($name, $default = null); $request­>getAttributes(); $request = $request­>withAttribute($name, $value); $request = $request­>withoutAttribute();                             
  37. 37. REFERENCES
  38. 38. by FIG PSR-7 metadocument FIG PSR-7 specifications PSR-7 by example @mwop

×