获取当前路由

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

// 通过此中间件,您可以从解析的路由中访问路由和路由结果
$app->add(function (Request $request, RequestHandler $handler) {
    $routeContext = RouteContext::fromRequest($request);
    $route = $routeContext->getRoute();

    // 对于不存在的路由,返回NotFound
    if (empty($route)) {
        throw new HttpNotFoundException($request);
    }

    $name = $route->getName();
    $groups = $route->getGroups();
    $methods = $route->getMethods();
    $arguments = $route->getArguments();

    // ... 做一些操作 ...

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

// 在CORS中间件之后添加RoutingMiddleware,以便首先进行路由
$app->addRoutingMiddleware();

// ErrorMiddleware应始终是最外层的中间件
$app->addErrorMiddleware(true, true, true);

// ...

$app->run();