Reference

The Request Handler Runner

Zend\HttpHandlerRunner\RequestHandlerRunner can be used to run a PSR-15 RequestHandlerInterface instance. By this, we mean:

  • Marshal a server request instance.
  • Handle exceptions due to marshaling the server request instance.
  • Pass the request to the composed request handler.
  • Pass the response generated by the request handler to the composed emitter

The runner takes four constructor arguments, in the following order:

  • A Psr\Http\Server\RequestHandlerInterface instance.
  • A Zend\HttpHandlerRunner\Emitter\EmitterInterface instance.
  • A PHP callable to generate a Psr\Http\Message\ServerRequestInterface instance.
  • A PHP callable that can generate a Psr\Http\Message\ResponseInterface instance given a PHP Throwable generated by the server request factory from the third argument.

Once constructed, you may call the method run():

$runner->run();

Server request factory

The $serverRequestFactory argument to the constructor may be any PHP callable that accepts no arguments (or all optional arguments), and which returns a PSR-7 ServerRequestInterface instance.

As an example, using zend-diactoros:

use Zend\Diactoros\ServerRequestFactory;

$serverRequestFactory = [ServerRequestFactory::class, 'fromGlobals'];

Alternately, a PSR-17 (proposed specification for HTTP message factories) factory may be used:

use HttpInterop\Implementation\ServerRequestFactory;

$serverRequestFactory = function () use ($_SERVER, $factory) {
    return $factory->createServerRequestFromArray($_SERVER);
};

Server request error response generator

In rare cases, the server request factory may raise a PHP Throwable or Exception. In those cases, the runner still needs to generate a response to emit.

The server request error response generator argument to the RequestHandlerRunner constructor may be any PHP callable that accepts a PHP Throwable argument, and which returns a PSR-7 ResponseInterface instance.

As an example, zend-stratigility provides the class Zend\Stratigility\Middleware\ErrorResponseGenerator, which is typically used with its ErrorHandler to generate a response. It can be re-purposed if we curry in empty server request and response instances as follows:

use Throwable;
use Zend\Diactoros\Response;
use Zend\Diactoros\ServerRequest;
use Zend\Stratigility\Middleware\ErrorResponseGenerator;

$errorResponseGenerator = function (Throwable $e) {
    $generator = new ErrorResponseGenerator();
    return $generator($e, new ServerRequest(), new Response());
};

Request handlers

Request handlers MUST implement Psr\Http\Server\RequestHandlerInterface. Additionally, for best results, they MUST provide their own error and exception handling, to ensure that a response is returned and the runner is able to emit a response.

Found a mistake or want to contribute to the documentation? Edit this page on GitHub!