获取当前路由

如果你需要在应用程序中访问当前路由,你需要使用传入的 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();