实施路由特定的中间件

时间:2019-03-09 12:19:13

标签: php psr-7

我已经设法将 request-handler aura-router 结合使用,并使用一个 router handler

我正在尝试实现特定于路由的中间件,而不是“全局”应用程序中间件。

$routerContainer = new RouterContainer();
$map = $routerContainer->getMap();

// Works fine...
$map->get('index', '/', 'App\Http\Controllers\HomeController::index');

// Error: Invalid request handler: array
$map->get('index', '/', [
    new SampleRouteMiddleware(),
    'App\Http\Controllers\HomeController::index'
]);

$request = ServerRequestFactory::fromGlobals($_SERVER, $_GET, $_POST, $_COOKIE, $_FILES);

$requestContainer = new RequestHandlerContainer();

$dispatcher = new Dispatcher([
    new SampleAppMiddleware(), // applies to all routes...
    new AuraRouter($routerContainer),
    new RequestHandler($requestContainer),
]);

$response = $dispatcher->dispatch($request);

1 个答案:

答案 0 :(得分:0)

您无法使用正在使用的PSR-15实现来做您想做的事情。您唯一的选择是编写具有以下结构的中间件:

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\MiddlewareInterface as Middleware;

class SampleMiddleware implements Middlware
{
    public function process(Request $request, Handler $handler): Response
    {
        if ($this->supports($request)) {
             // Do something specific to your middleware
        }

        return $handler->handle($request);
    }

    public function supports(Request $request): bool
    {
        // Write the conditions that make the SampleMiddleware take action. i.e.,
        return $request->getPath() === "/sample";
    }

}

此中间件仅处理路径为“ / sample”的请求。