检索当前路由

如果你需要在应用程序中获取当前的路由,你所需要做但就是,调用 HTTP 请求类的带有 "route" 参数的 getAttribute 方法,它将返回当前的路由,这个路由是 SlimRoute 类的实例。class.

可以使用 getName() 获取路由的名称,或者使用 getMethods()获取此路由支持的方法, etc。

Note: 如果你需要在 app 中间件中访问路由,必须在配置中将 "determineRouteBeforeAppMiddleware" 设置为 true。否则,getAttribute("route") 将会返回 null。该路由在路由中间件中永远可用。

Example:

use SlimHttpRequest;
use SlimHttpResponse;
use SlimApp;

$app = new App([
    "settings" => [
        // Only set this if you need access to route within middleware
        "determineRouteBeforeAppMiddleware" => true
    ]
])

// routes...
$app->add(function (Request $request, Response $response, callable $next) {
    $route = $request->getAttribute("route");
    $name = $route->getName();
    $groups = $route->getGroups();
    $methods = $route->getMethods();
    $arguments = $route->getArguments();

    // do something with that information

    return $next($request, $response);
});
文章导航