# 获取当前路由
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