# 路由对象
Sometimes in middleware you require the parameter of your route.
In this example we are checking first that the user is logged in and second that the user has permissions to view the particular video they are attempting to view.
> 有时在中间件中需要路由的参数。
>
> 在本例中,我们首先检查用户是否登录,然后检查用户是否有权限查看他们要查看的特定视频。
~~~php
<?php
$app
->get('/course/{id}', Video::class.":watch")
->add(PermissionMiddleware::class);
~~~
~~~php
<?php
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use Slim\Routing\RouteContext;
class PermissionMiddleware {
public function __invoke(Request $request, RequestHandler $handler) {
$routeContext = RouteContext::fromRequest($request);
$route = $routeContext->getRoute();
$courseId = $route->getArgument('id');
// ...do permission logic...
return $handler->handle($request);
}
}
~~~
## Obtain Base Path From Within Route从路由内获取基本路径
> 要从一个路由中获取基本路径,只需执行以下操作:
To obtain the base path from within a route simply do the following:
~~~php
<?php
use Slim\Factory\AppFactory;
use Slim\Routing\RouteContext;
require __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
$app->get('/', function($request, $response) {
$routeContext = RouteContext::fromRequest($request);
$basePath = $routeContext->getBasePath();
// ...
return $response;
});
~~~
## Attributes属性
With PSR-7 it is possible to inject objects/values into the request object for further processing. In your applications middleware often need to pass along information to your route closure and the way to do is it is to add it to the request object via an attribute.
> 使用PSR-7可以将对象/值注入到请求对象中进行进一步处理。在您的应用程序中,中间件通常需要将信息传递给路由闭包,方法是通过属性将其添加到请求对象中。
Example, Setting a value on your request object.
~~~php
$app->add(function ($request, $handler) {
// add the session storage to your request as [READ-ONLY]
$request = $request->withAttribute('session', $_SESSION);
return $handler->handle($request);
});
~~~
Example, how to retrieve the value.
~~~php
$app->get('/test', function ($request, $response, $args) {
$session = $request->getAttribute('session'); // get the session from the request
return $response->write('Yay, ' . $session['name']);
});
~~~
The request object also has bulk functions as well.`$request->getAttributes()`and`$request->withAttributes()`
> 请求对象也有批量函数。`$request->getAttributes() '和' $request->withAttributes() `
- 开始
- 安装
- 升级指南
- Web服务器
- 概念
- 生命周期
- PSR 7
- 中间件
- 依赖容器
- 实例 及通知和警告处理
- Request
- 请求方法
- 请求头信息
- 请求主体
- 上传的文件
- 请求帮助
- 路由对象
- Response
- 响应状态
- 响应标头
- 响应体
- 返回JSON
- 视图模板
- 路由
- 创建路由
- 路由回调
- 路由策略
- 路线占位符
- 路由名
- 路由组
- 路由中间件
- 路由表达式缓存
- 容器识别解析
- 封装中间件
- 路由的中间件
- 错误处理中间件
- 方法重写的中间件
- 输出缓冲中间件
- 内容长度中间件
- 扩展功能
- 以 / 结尾的路由模式
- 获取当前路由
- 设置CORS
- 使用POST表单上传文件
- 第三方组件
- slim-session
- auth
- slim-api-skeleton
- dir