ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# 路由对象 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() `