psr-7 http messages
TRANSCRIPT
PSR-7Tobias Nyholm
PHP 7
PSR-7 from PHP-FIG
PHP-Fig
StandardsPSR-0 PSR-1 PSR-2 PSR-3 PSR-4 PSR-5 PSR-6 PSR-7 PSR-8 PSR-9 PSR-10
Autoloading Basic coding standard Coding style Logger Autoloading PHPDoc (draft) Caching (review) HTTP Messages Huggable interface (draft) Security Disclosure (draft) Security Advisories (draft)
PSR-8
About me• Tobias Nyholm, @tobiasnyholm
• Happyr.com
• Certified Symfony developer
• Your organizer
PSR-7
Standard interfaces for HTTP messages
Why do we need PSR-7?We could write framework agnostic code like: • Routers • Controllers • Cache • Logging • Authentication • etc…
GET /startpage HTTP/1.1 Host: xkcd.com Accept: text/html User-Agent: Mozilla/5.0 (Macintosh)
HTTP/1.1 200 OK Date: Sat, 02 Apr 2011 21:05:05 GMT Server: lighttpd/1.4.19 Content-Type: text/html
<html> <!-- ... HTML for the xkcd comic --> </html>
In PHP
The interfaces• MessageInterface • ResponseInterface • RequestInterface • ServerRequestInterface • UriInterface • StreamInterface • UploadedFileInterface
Client request
POST /send-message HTTP/1.0 Location: www.example.com Content-Type: application/x-www-form-urlencoded Content-Length: 33
from=Tobias&to=all&message=hello
MessageInterface
RequestInterface UriInterface
What to care about?RequestInterfacegetMethod getRequestTarget getUri
getProtocolVersion getHeaders getHeader hasHeader getBody
ResponseInterfacegetStatusCode getReasonPhrase
getProtocolVersion getHeaders getHeader hasHeader getBody
Getting headers
PSR-7 objects are immutable
Mutable vs immutable
• Mutable - edit
• Immutable - read only
No settersRequestInterfacewithMethod withRequestTarget withUri
withProtocolVersion withHeader withAddedHeader withoutHeader withBody
ResponseInterfacewithStatus
withProtocolVersion withHeader withAddedHeader withoutHeader withBody
DateTime is mutable
Don’t do this
With*
Streams
StreamsStreamInterface__toString isReadable isSeekable isWriteable getSize read write seek rewind close …
Use it as it was a string
Middleware
Add header to all responses
Adapters
All adapters in one place
• PHP-HTTP
• http://php-http.readthedocs.org/en/latest/
• Will replace Ivory(https://github.com/egeloen/ivory-http-adapter)
Composer.json
Start using it
Read more at
• http://www.php-fig.org/psr/psr-7/
• https://github.com/php-http
• https://github.com/oscarotero/psr7-middlewares
• https://github.com/Happyr/HttpAutoDiscovery