Simple (but powerful) PSR-15 middleware dispatcher:
- PHP 7
- A PSR-7 Message implementation, for example zend-diactoros
- Optionally, a PSR-11 container implementation to create the middleware components on demand.
use Middleland\Dispatcher;
$middleware = [
new Middleware1(),
new Middleware2(),
new Middleware3(),
//You can nest middleware frames
new Dispatcher([
new Middleware4(),
new Middleware5(),
]),
//Or use closures
function ($request, $next) {
$response = $next->process($request);
return $response->withHeader('X-Foo', 'Bar');
},
//Or use a string to create the middleware on demand using PSR-11 container
'middleware6'
//USE AN ARRAY TO ADD CONDITIONS:
//This middleware is processed only in paths starting by "/admin"
['/admin', new MiddlewareAdmin()],
//and this is processed in DEV
[ENV === 'DEV', new MiddlewareAdmin()],
//we can use callables to use middlewares only in some conditions
[
function ($request) {
return $request->getUri()->getScheme() === 'https';
},
new MiddlewareHttps()
],
//or use the provided matchers
[new Pattern('*.png'), new MiddlewareForPngFiles()],
//And use several for each middleware component
[ENV === 'DEV', new Pattern('*.png'), new MiddlewareForPngFilesInDev()],
];
$dispatcher = new Dispatcher($middleware, new Container());
$response = $dispatcher->dispatch(new Request());
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:
Name | Description | Example |
---|---|---|
Path |
Filter requests by base path. Use exclamation mark for negative matches | new Path('/admin') , new Path('!/not-admin') |
Pattern |
Filter requests by path pattern. Use exclamation mark for negative matches | new Pattern('*.png') new Pattern('!*.jpg') |
Accept |
Filter requests by Accept header. Use exclamation mark for negative matches | new Accept('text/html') new Accept('!image/png') |
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.