equip / dispatch
An HTTP Interop compatible middleware dispatcher
Installs: 311 994
Dependents: 14
Suggesters: 0
Security: 0
Stars: 25
Watchers: 11
Forks: 2
Open Issues: 1
Requires
- php: >=7.0
- psr/http-server-middleware: ^1.0
Requires (Dev)
- eloquent/liberator: ^2.0
- eloquent/phony-phpunit: ^3.0
- phpunit/phpunit: ^6.0
README
An HTTP Interop compatible middleware dispatcher in Equip. Attempts to be PSR-1, PSR-2, PSR-4, PSR-7, and PSR-15 compliant.
Heavily influenced by the design of Tari by ircmaxwell.
For more information, see the documentation.
Install
composer require equip/dispatch
Usage
The MiddlewareCollection
is a container for middleware that acts as the entry point.
It takes two arguments:
- An array of
$middleware
which must be instances of server middleware. - A callable
$default
that acts as the terminator for the collection and returns an empty response.
Once the collection is prepared it can dispatched with a server request and will return the response for output.
Example
use Equip\Dispatch\MiddlewareCollection; // Any implementation of PSR-15 MiddlewareInterface $middleware = [ new FooMiddleware(), // ... ]; // Default handler for end of collection $default = function (ServerRequestInterface $request) { // Any implementation of PSR-7 ResponseInterface return new Response(); }; $collection = new MiddlewareCollection($middleware); // Any implementation of PSR-7 ServerRequestInterface $request = ServerRequest::fromGlobals(); $response = $collection->dispatch($request, $default);
Nested Collections
The MiddlewareCollection
also implements the MiddlewareInterface
to allow
collections to be nested:
use Equip\Dispatch\MiddlewareCollection; // Any implementation of PSR-15 MiddlewareInterface $middleware = [ new FooMiddleware(), // A nested collection new MiddlewareCollection(...), // More middleware new BarMiddleware(), // ... ]; $collection = new MiddlewareCollection($middleware); // HTTP factories can also be used $default = [$responseFactory, 'createResponse']; $request = $serverRequestFactory->createRequest($_SERVER); $response = $collection->dispatch($request, $default);