本文介绍了获取 Symfony 服务中的路由名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试在 Symfony 4 服务中获取当前路由的名称.
Im try to get the name of the current route in a Symfony 4 service.
routes.yaml
test-route:
path: /test
controller: App\Controller\Test::test
服务
class Myservice {
private $u;
public function __construct(Utilities $u){
$this->u = $u;
$route = getRouteSomehow(); // should return "test-route"
}
}
我找到了这段代码来抓取路线:
I found this piece of code to grab the route:
$requestStack->getCurrentRequest()->get('_route');
..但不确定在哪里/如何/注入什么才能使用它.
..but not sure where/how/what to inject to be able to use it.
也许还有一个更简单的.
Perhaps there's a simpler was as well.
推荐答案
如果你使用 symfony4,并且自动装配 (https://symfony.com/doc/current/service_container/autowiring.html),你可以注入 request_stack 服务如下:
If you use symfony4, and autowire (https://symfony.com/doc/current/service_container/autowiring.html), you can inject request_stack service as following:
use Symfony\Component\HttpFoundation\RequestStack;
class Myservice {
private $u;
public function __construct(Utilities $u, RequestStack $requestStack) {
$this->u = $u;
$route = $requestStack->getCurrentRequest()->get('_route');
}
}
这篇关于获取 Symfony 服务中的路由名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!