检索当前路线

如果您需要访问应用程序中的当前路由,则需要RouteContext使用传入的ServerRequestInterface.

从那里你可以获取路由 via$routeContext->getRoute()并通过使用访问路由名称getName()或获取此路由支持的方法 viagetMethods()等。

注意:如果您需要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();