0

我设法将request-handleraura-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);
4

1 回答 1

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”的请求。

于 2019-03-09T12:31:44.397 回答