从 SLIM 3 中的组路由获取路由参数 PHP
Get Route parameter from group route in SLIM 3 PHP
我在中间件中获取组路由参数时遇到问题,这就是我正在做的事情
我正在使用 [PHP - SLIM 3 Framework]
route.php
$app->group('/{lang}', function() use ($container){
//routes ... (ignore the other routes)
})->add(new Middleware($container));
Middleware.php
//middleware.php
class Middleware {
public function __invoke($req, $res, $next)
{
//here is the part which is confusing about how can i get
// {lang} parameter
$req->getAttribute('route')
}
}
您可以使用 getArguments()
方法
public function __invoke($req, $res, $next)
{
$route = $req->getAttribute('route');
$args = $route->getArguments();
$lang = $args['lang'];
return $res;
}
注意:您还需要将 slim 设置 determineRouteBeforeAppMiddleware
设置为 true。否则参数不会在中间件中设置。
$container = [
'settings' => [
'determineRouteBeforeAppMiddleware' => true
]
]
$app = new \Slim\App($container);
我在中间件中获取组路由参数时遇到问题,这就是我正在做的事情
我正在使用 [PHP - SLIM 3 Framework]
route.php
$app->group('/{lang}', function() use ($container){
//routes ... (ignore the other routes)
})->add(new Middleware($container));
Middleware.php
//middleware.php
class Middleware {
public function __invoke($req, $res, $next)
{
//here is the part which is confusing about how can i get
// {lang} parameter
$req->getAttribute('route')
}
}
您可以使用 getArguments()
方法
public function __invoke($req, $res, $next)
{
$route = $req->getAttribute('route');
$args = $route->getArguments();
$lang = $args['lang'];
return $res;
}
注意:您还需要将 slim 设置 determineRouteBeforeAppMiddleware
设置为 true。否则参数不会在中间件中设置。
$container = [
'settings' => [
'determineRouteBeforeAppMiddleware' => true
]
]
$app = new \Slim\App($container);