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?

RokDev
  • 161
  • 1
  • 10

2 Answers2

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();
    // ...
}
RokDev
  • 161
  • 1
  • 10
7

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

$router = $this->get('router');
$routes = $router->getRouteCollection()->all();
Zeppe
  • 83
  • 7
  • 4
    you should always add an explanation so people understand rather than know how-to – treyBake May 30 '18 at 12:20
  • 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.* – Loek May 30 '18 at 12:23
  • All controller methods have access to container resoureces? – Zeppe May 30 '18 at 12:27
  • @Zeppe 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. – Cerad May 30 '18 at 12:46
  • 1
    @RokDev - 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. – Cerad May 30 '18 at 12:47
  • @Cerad, I guess this is / was my problem, the class is _not_ extending any base controller class. Thanks! – RokDev May 30 '18 at 12:51
  • 1
    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. – Cerad May 30 '18 at 12:53