Question about PSR-15 in Expressive


Hello all,

I’ve just installed Zend Expressive 3 RC1 and I would like to know if I’m wrong on my comprehension of PSR-15.

The basic routes are :

$app->get('/', App\Handler\HomePageHandler::class, 'home');
$app->get('/api/ping', App\Handler\PingHandler::class, '');

The registered middlewares for those routes implements RequestHandlerInterface, not MiddlewareInterface.

In this case, I think the classes implements RequestHandlerInterface because it returns directly a response.

return new HtmlResponse($this->template->render('app::home-page', $data));
return new JsonResponse(['ack' => time()]);

but I could have achieved the same thing with a class implementing MiddlewareInterface ?!

So if I don’t need to call another middleware I can use a class implementing RequestHandlerInterface otherwise MiddlewareInterface.

Am I wrong ?



That’s exactly correct.

For the inner-most item of any pipeline, you want something that will be guaranteed to return a response. If that item does not need to call on the handler passed to it… it can itself be a request handler.

We recommend that you create request handlers for handling routes. You can still use middleware pipelines for routes as well; just make sure your request handler is the last item in the pipeline:

$app->post('/api/books', [
    CreateBookHandler::class,            // <-- Request handler!

The rule of thumb is:

  • Is there any path through the class that will require delegating handling of the request? If so, it’s middleware.
  • Can the class always produce a response on its own? If so, it’s a request handler.