让类似Slim(v3)的组:
$app->group('/user/{user_id}', function(App $app) {
// HERE
$app->get('/stuff', function(Request $request, Response $response) {
$userId = $request->getAttribute('user_id');
// ... get stuff of user
});
$app->get('/otherstuff', function(Request $request, Response $response) {
$userId = $request->getAttribute('user_id'); // repetition!
// ... get other stuff of user
});
});
是否有一种方法可以访问组函数中的$request
(以及URL参数),以避免每个函数中的重复重复?
您可以通过容器通过$request
方法访问group()
对象。
$req = $app->getContainer()->get('request');
但是使用NULL
方法会得到getAttribute()
。在您的情况下,不应使用从容器中检索到的请求,因为如有必要,可以更改请求的状态。
Request和Response对象是不可变的。这些属性可以根据获取请求对象的时间而有所不同。 finished Request对象将在您的操作结束时移交。因此,请在操作中使用它。
但是您仍然可以获取路径并获取user_id
的URL参数。
$path = $req->getUri()->getPath();
$user_id = explode('/', $path)[2];
要说的是,group()
方法旨在帮助您将路由组织成逻辑组。如果要干燥代码,请创建具有所需操作的类。例如:
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Container\ContainerInterface;
class UserController
{
protected $container;
protected $userId;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
$this->userId = $this->user();
}
public function stuff(Request $request, Response $response)
{
// Use $this->userId here
}
public function otherStuff(Request $request, Response $response)
{
// Use $this->userId here
}
protected function user()
{
$path = $this->container->get('request')->getUri()->getPath();
$parts = explode('/', $path);
return $parts[2] ?? '';
}
}
然后,更新您的路线:
$app->group('/user/{user_id}', function(App $app) {
$app->get('/stuff', UserController::class . ':stuff');
$app->get('/otherstuff', UserController::class . ':otherStuff');
});
或者,您可以从路线参数中获得$user_id
:
class UserController
{
protected $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function stuff(Request $request, Response $response, array $args)
{
// Use $args['user_id'] here
}
public function otherStuff(Request $request, Response $response, array $args)
{
// Use $args['user_id'] here
}
}
或者,如果您更喜欢闭包:
$app->group('/user/{user_id}', function(App $app) {
$app->get('/stuff', function(Request $request, Response $response, array $args) {
// Use $args['user_id'] here
});
$app->get('/otherstuff', function(Request $request, Response $response, array $args) {
// Use $args['user_id'] here
});
});