Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Modern HTTP handling with PHP - Confoo Montreal...

Modern HTTP handling with PHP - Confoo Montreal 2018

PSR-7 describes common interfaces for representing HTTP messages. HTTP messages are the foundation of web development. Web browsers and HTTP clients such as cURL create HTTP request messages that are sent to a web server, which provides an HTTP response message. Server-side code receives an HTTP request message, and returns an HTTP response message.

Hannes Van De Vreken

March 09, 2018
Tweet

More Decks by Hannes Van De Vreken

Other Decks in Programming

Transcript

  1. !

  2. Common interfaces for HTTP messages - Works in any Framework

    - Both for HTTP Clients and HTTP applications - HTTP version independent PSR/HTTP-MESSAGE
  3. PSR/HTTP-MESSAGE interface RequestInterface { function getProtocolVersion(); function getHeaders(); function getHeader($name);

    function getHeaderLine($name); function getBody(); … } interface ResponseInterface { function getProtocolVersion(); function getHeaders(); function getHeader($name); function getHeaderLine($name); function getBody(); … }
  4. PSR/HTTP-MESSAGE interface RequestInterface implements MessageInterface { function getRequestTarget(); function getUri();

    function getMethod(); } interface ResponseInterface implements MessageInterface { function getStatusCode(); function getReasonPhrase(); }
  5. START USING PSR-7 IN YOUR APP Symfony request/response object ⁷

    ⁷ ⁷ Zend-Diactoros request/response object
  6. START USING PSR-7 IN YOUR APP Symfony request/response object ⁷

    ⁷ ⁷ Zend-Diactoros request/response object \Psr\Http\Message\RequestInterface type hinted
  7. MIDDLEWARE DEFINITION function process( ServerRequestInterface $request, RequestHandlerInterface $handler ) {

    // Alter request, if you want $response = $handler->handle($request); // Alter response, if you want return $response; }
  8. GUZZLEHTTP/GUZZLE - PROMISES use Psr\Http\Message\ResponseInterface as Res; $promise = $client->sendAsync($request);

    $promise->then(function (Res $response) { $response->getBody(); }); $promise->wait();
  9. GUZZLEHTTP/GUZZLE - MIDDLEWARES $middleware = function ($handler) { return function

    ($request, $options) use ($handler) { // Alter request, if you want return $handler($request, $options) ->then(function (ResponseInterface $response) { // Alter response, if you want return $response; }); }; }