如果您需要在應用程式中存取目前的路由,您將需要使用即將到來的 ServerRequestInterface
實體化 RouteContext
物件。
在此您可以透過 $routeContext->getRoute()
取得路由,並透過 getName()
存取路由的名稱,或是透過 getMethods()
取得該路由支援的方法等。
注意:如果您需要在路由處理程式之前的中介軟體週期中存取 RouteContext
物件,您將需要在錯誤處理中介軟體之前將 RoutingMiddleware
新增為最外層中介軟體(請見下方範例)。
範例
<?php
use Slim\Exception\HttpNotFoundException;
use Slim\Factory\AppFactory;
use Slim\Routing\RouteContext;
require __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
// Via this middleware you could access the route and routing results from the resolved route
$app->add(function (Request $request, RequestHandler $handler) {
$routeContext = RouteContext::fromRequest($request);
$route = $routeContext->getRoute();
// return NotFound for non-existent route
if (empty($route)) {
throw new HttpNotFoundException($request);
}
$name = $route->getName();
$groups = $route->getGroups();
$methods = $route->getMethods();
$arguments = $route->getArguments();
// ... do something with the data ...
return $handler->handle($request);
});
// The RoutingMiddleware should be added after our CORS middleware so routing is performed first
$app->addRoutingMiddleware();
// The ErrorMiddleware should always be the outermost middleware
$app->addErrorMiddleware(true, true, true);
// ...
$app->run();