Symfony Tips & Tricks: Named Routes
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:
Well, to generate a URL for this action, all you need to do is this:
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:
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!
Originally published at https://www.bornfight.com.