Symfony Tips & Tricks: Named Routes

Author Marko Kruljac
Category Development
Date Aug 09, 2019
2 min read

How many times have you renamed your controller actions or controllers themselves, only to see all your links break because now they are pointing to an old URL?

If you worked in Yii, you would do something like this:

<?php

return Url::to(['site/foo']);

Now, if you ever changed your controller or action name, you’d be in trouble.

Whats’s the deal with Symfony

Symfony, on the other hand, has a concept of internal route names that you can use for generating links.

Take for example this controller:

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;

class DefaultController extends AbstractController
{
     /**
      * Matches /foo exactly
      *
      * @Route("/foo", name="my_unique_route_name")
      */
     public function foo()
     {
          // ...
     }
}

Well, to generate a URL for this action, all you need to do is this:

// src/Service/SomeService.php

use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class SomeService
{
     private $router;

     public function __construct(UrlGeneratorInterface $router)
     {
          $this->router = $router;
     }

     public function someMethod()
     {
          $url = $this->router->generate(
               'my_unique_route_name'
          );
          // ...
     }
}

This way, if you ever change the route (for example from /foo to /bar) or rename the controller or action, the URL generator will still work.

You can check this by running the console debugger:

./bin/console debug:router

And if I make a mistake

What happens if you mistype this internal route name, or change it without understanding the consequence? Well, the URL generator will no longer know how to generate the route, but luckily there are awesome PhpStorm Symfony plugins that will notify you of this error (statically, without running the code).

These plugins are:

  1. Symfony Support
  2. PHP Toolbox
  3. PHP Annotations

Here is what it looks when you mistake the URL.

Pretty sweet, right? When you do give it a good route name, you can just cmd+click the string and PhpStorm will jump to the controller that implements the action. But that’s not all, it gets even better – as PhpStorm knows all your available routes, it will auto-suggest what to use.

And that’s it – happy coding!

__________
We’re available for partnerships and open for new projects. If you have an idea you’d like to discuss, share it with our team!

Subscribe to our newsletter

Subscribe now and get our top news once a month.

100% development, design & strategy.

100% spam-free.

You're now a part of our club!

We got your e-mail address and you'll get our next newsletter!