# 路由對象
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