Get the route name in a Symfony service [duplicate]

和自甴很熟 提交于 2020-12-13 03:45:07

问题


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

service

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.


回答1:


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');
    }
}


来源:https://stackoverflow.com/questions/52211606/get-the-route-name-in-a-symfony-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!