oscarotero / middleland
PSR-15 中间件分发器
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
简单(但强大)的 PSR-15 中间件分发器
需求
- PHP 7
- 需要实现 PSR-7 Message,例如 laminas-diactoros
- 可选,一个 PSR-11 container 实现以按需创建中间件组件。
示例
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());
匹配器
如上例所示,您可以使用一个“匹配器”数组来过滤接收中间件的请求。您可以使用可调用、Middleland\Matchers\MatcherInterface
的实例或布尔值,但为了方便,也使用字符串值来创建 Middleland\Matchers\Path
实例。可用的匹配器有
如何创建匹配器
只需使用可调用或 Middleland\Matchers\MatcherInterface
的实例。示例
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'; } }
请参阅 CHANGELOG 了解有关最近更改的更多信息。
MIT 许可证(MIT)。请参阅 LICENSE 了解更多信息。