oscarotero / middleland
PSR-15 middleware dispatcher
v1.0.1
2020-12-06 00:59 UTC
Requires
- php: ^7.0|^8.0
- psr/container: ^1.0
- psr/http-server-middleware: ^1.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.0
- laminas/laminas-diactoros: ^1.3
- phpunit/phpunit: >=6.0
README
Simple (but powerful) PSR-15 middleware dispatcher:
Requirements
- PHP 7
- A PSR-7 Message implementation, for example laminas-diactoros
- Optionally, a PSR-11 container implementation to create the middleware components on demand.
Example
use Middleland\Dispatcher; $middleware = [ new Middleware1(), new Middleware2(), new Middleware3(), // A dispatcher can be used to group middlewares new Dispatcher([ new Middleware4(), new Middleware5(), ]), // You can use closures function ($request, $next) { $response = $next->handle($request); return $response->withHeader('X-Foo', 'Bar'); }, // Or use a string to create the middleware on demand using a PSR-11 container 'middleware6' // USE AN ARRAY TO ADD CONDITIONS: // This middleware is processed only in paths starting by "/admin" ['/admin', new MiddlewareAdmin()], // This is processed in DEV [ENV === 'DEV', new MiddlewareAdmin()], // Use callables to create other conditions [ function ($request) { return $request->getUri()->getScheme() === 'https'; }, new MiddlewareHttps() ], // There are some matchers included in this library to create conditions [ new Pattern('*.png'), new MiddlewareForPngFiles() ], //And use several for each middleware [ ENV === 'DEV', new Pattern('*.png'), new MiddlewareForPngFilesInDev() ], ]; $dispatcher = new Dispatcher($middleware, new Container()); $response = $dispatcher->dispatch(new Request());
Matchers
As you can see in the example above, you can use an array of "matchers" to filter the requests that receive middlewares. You can use callables, instances of Middleland\Matchers\MatcherInterface
or booleans, but for comodity, the string values are also used to create Middleland\Matchers\Path
instances. The available matchers are:
How to create matchers
Just use a callable or an instance of the Middleland\Matchers\MatcherInterface
. Example:
use Middleland\Matchers\MatcherInterface; use Psr\Http\Message\ServerRequestInterface; class IsAjax implements MatcherInterface { public function __invoke(ServerRequestInterface $request): bool { return $request->getHeaderLine('X-Requested-With') === 'xmlhttprequest'; } }
Please see CHANGELOG for more information about recent changes.
The MIT License (MIT). Please see LICENSE for more information.