2

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.

yevg
  • 1,846
  • 9
  • 34
  • 70
  • 2
    Inject the [request stack](https://symfony.com/blog/new-in-symfony-2-4-the-request-stack) service. – Cerad Sep 06 '18 at 20:23

1 Answers1

8

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');
    }
}
Phantom
  • 362
  • 3
  • 10