Getting all the routes of a Symfony application

Published on 2023-03-31 • Modified on 2023-03-31

This snippet shows how to get all the routes of a Symfony application. Here, we display all the routes starting with blog_ which belongs to the BlogController.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

use Symfony\Component\Routing\RouterInterface;

use function Symfony\Component\String\u;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 *
 * @property RouterInterface $router
 */
trait Snippet249Trait
{
    public function snippet249(): void
    {
        $collection = $this->router->getRouteCollection();
        $allRoutes = $collection->all();
        foreach ($allRoutes as $name => $route) {
            if (u($name)->startsWith('blog_')) {
                echo $name.' - '.$route->getDefault('_controller').' - '.$route->getPath().PHP_EOL;
            }
        }

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  Random snippet

  Work with me!