codeinc / middleware-dispatcher
Code Inc. PSR15 middleware dispatcher
Requires
- php: >=7.1
- codeinc/collection-interface: ^1.1
- codeinc/psr7-responses: ^2
- psr/http-server-middleware: ^1.0
Requires (Dev)
- phpunit/phpunit: ^7
Suggests
- codeinc/psr7-response-sender: A PSR-7 response sender
README
codeinc/middleware-dispatcher
is a PSR-15 middleware dispatcher. The middleware dispatcher behaves as a PSR-15 RequestHandlerInterface
. It comes in two forms, an abstract class AbstractMiddlewareDispatcher
to be extended and a final class MiddlewareDispatcher
.
If none of middleware added to the dispatcher can process the request, a final request handler is called. By default this request handler is DefaultFinalRequestHandler
which returns a NotFoundResponse
.
Usage
<?php use CodeInc\MiddlewareDispatcher\MiddlewareDispatcher; // instantiating the dispatcher $dispatcher = new MiddlewareDispatcher([ new MyFirstMiddleware(), new MySecondMiddleware() ]); $dispatcher->addMiddleware(new MyThirdMiddleware()); // handling the request // will return a NoResponseAvailable object if the request can not be processed by the middleware // --> $psr7ServerRequest must be an object implementing ServerRequestInterface $psr7Response = $dispatcher->handle($psr7ServerRequest);
An alternative dispatcher called MiddlewareIteratorDispatcher
allows to use an iterator as source for the dispatcher. Below is an example using a generator. In this example, the middleware objects are instantiated on the fly. This avoids instantiating unsued middleware objects. If the first middleware is capable of generating a valid response, the next ones will never be instantiated.
<?php use CodeInc\MiddlewareDispatcher\MiddlewareIteratorDispatcher; $dispatcher = new MiddlewareIteratorDispatcher(function():Generator { yield new MyFirstMiddleware(); yield new MySecondMiddleware(); yield new MyThirdMiddleware(); }); $psr7Response = $dispatcher->handle($psr7ServerRequest);
Installation
This library is available through Packagist and can be installed using Composer:
composer require codeinc/middleware-dispatcher
License
This library is published under the MIT license (see the LICENSE
file).