Symfony 4 print all routes
Asked Answered
M

2

5

I'm trying to set up an index page which would print out all the endpoints in the API (using Symfony 4).

In Symfony 2 you could get a router and via the container and then the collection of the routes. But it seems that you don't have access to the container right out of the box in Symfony 4.

Google search doesn't seem to yield precise result I'm looking for. Is there an alternative way to do so in Symfony 4 or something alike?

Miscreant answered 30/5, 2018 at 12:15 Comment(2)
why not use php's exec function to run php bin/console debug:router?Keystroke
I'd like to have more freedom, for example have them in a collection so I could iterate and suchMiscreant
M
11

So I put the pieces together:

Simplest way seems to be to inject Symfony\Component\Routing\RouterInterface and then use it as a Router. As I mentioned in the question, you can get the routes by using $router->getRouteCollection()->all() where $router is the injected dependency.

E.g.:

use Symfony\Component\Routing\RouterInterface;

public function someMethodInController(Request $request, RouterInterface $router)
{
    $routes = $router->getRouteCollection()->all();
    // ...
}
Miscreant answered 30/5, 2018 at 12:30 Comment(0)
A
7

Use in any controller, this will return you an array of avaiable route objects.

$router = $this->get('router');
$routes = $router->getRouteCollection()->all();
Asclepiadean answered 30/5, 2018 at 12:19 Comment(7)
you should always add an explanation so people understand rather than know how-toKeystroke
Fair enough, but OP provided it himself almost literally: In Symfony 2 you could get a router and via the container and then the collection of the routes.Messeigneurs
All controller methods have access to container resoureces?Asclepiadean
@Asclepiadean Starting in S3.4, 4 There is a new base controller class called AbstractController. If your controller extends from it then you no longer have general access to the container. There are however some services you can access of which router is one. So what you posted should actually work. But injecting this sort of thing is recommended.Spae
@Miscreant - What class does your controller extend from? While injecting is "better", $this->get('router'); really should have worked assuming you are using one of the Symfony base controller classes.Spae
@Cerad, I guess this is / was my problem, the class is not extending any base controller class. Thanks!Miscreant
Which is fine if you can do it. As long as you don't need the helper functions defined in ControllerTrait then no base controller class is good.Spae

© 2022 - 2024 — McMap. All rights reserved.