# 獲取當前路由
If you ever need to get access to the current route within your application, you will need to instantiate the`RouteContext`object using the incoming`ServerRequestInterface`.
From there you can get the route via`$routeContext->getRoute()`and access the route’s name by using`getName()`or get the methods supported by this route via`getMethods()`, etc.
Note: If you need to access the`RouteContext`object during the middleware cycle before reaching the route handler you will need to add the`RoutingMiddleware`as the outermost middleware before the error handling middleware (See example below).
Example:
~~~
<?php
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 NotFoundException($request, $response);
}
$name = $route->getName();
$groups = $route->getGroups();
$methods = $route->getMethods();
$arguments = $route->getArguments();
// ... do something with the data ...
return $handler->handle($request);
});
//路由中間件應該在我們的CORS中間件之后添加,所以先執行路由
// The RoutingMiddleware should be added after our CORS middleware so routing is performed first
$app->addRoutingMiddleware();
// ...
$app->run();
~~~
- 開始
- 安裝
- 升級指南
- Web服務器
- 概念
- 生命周期
- PSR 7
- 中間件
- 依賴容器
- 實例 及通知和警告處理
- Request
- 請求方法
- 請求頭信息
- 請求主體
- 上傳的文件
- 請求幫助
- 路由對象
- Response
- 響應狀態
- 響應標頭
- 響應體
- 返回JSON
- 視圖模板
- 路由
- 創建路由
- 路由回調
- 路由策略
- 路線占位符
- 路由名
- 路由組
- 路由中間件
- 路由表達式緩存
- 容器識別解析
- 封裝中間件
- 路由的中間件
- 錯誤處理中間件
- 方法重寫的中間件
- 輸出緩沖中間件
- 內容長度中間件
- 擴展功能
- 以 / 結尾的路由模式
- 獲取當前路由
- 設置CORS
- 使用POST表單上傳文件
- 第三方組件
- slim-session
- auth
- slim-api-skeleton
- dir