Search code examples
symfonysymfony-routing

How to generate an URL for a controller in Symfony?


I know how to generate an URL for a route. However now I need to generate an URL for a controller or for a controller with a method. I checked the sourced of UrlGenerator but did not find any relevant information. No information in Symfony docs as well.

The method of the controller has an associate url. This url will be used in controller but I need the generator to be a service.


Solution

  • So, here is the service. At least an example of how it could implemented. SF4

    namespace App\Route;
    
    use Symfony\Component\Routing\RouteCollection;
    use Symfony\Component\Routing\RouterInterface;
    
    class UrlGenerator
    {
        /**
         * @var RouteCollection
         */
        private $collection;
    
        public function __construct(RouterInterface $router)
        {
            $this->collection = $router->getRouteCollection();
        }
    
        public function generate(string $controllerClass, string $method): string
        {
            foreach ($this->collection as $item) {
                $defaults = $item->getDefaults();
                $controllerPath = $defaults['_controller'];
                $parts = explode('::', $controllerPath);
    
                if ($parts[0] !== $controllerClass) {
                    continue;
                }
    
                if ($parts[1] !== $method) {
                    continue;
                }
    
                return $item->getPath();
            }
    
            throw new \RuntimeException(
                'Route for such combination of controller and method is absent'
            );
        }
    }
    
    

    Poorly tested but working solution.