New in Symfony 5.1: Route annotations priority
March 16, 2020 • Published by Javier Eguiluz
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
Contributed by
Nicolas Grekas
in #35608.
Symfony routes can include variable parts called parameters to match different URLs sharing the same structure. Although you can restrict the values of each route parameters, two or more routes can match the same URL.
In those cases Symfony uses the route that was defined first. If you define the routes using YAML, XML or PHP files, you can reorder the routes to fit your needs. However, when using annotations to define routes, reordering can be much harder.
That's why in Symfony 5.1 we've added a route priority option, but only for
annotations. As usual in other parts of Symfony, priority is a positive or
negative integer which defaults to 0
. The higher its value, the more priority
the route has:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
class MyController extends AbstractController
{
/**
* @Route("/{some_parameter}", name="route1")
*/
public function someMethod(): Response
{
// ...
}
/**
* @Route("/foo", priority=10, name="route2")
*/
public function anotherMethod(): Response
{
// ...
}
}
In Symfony 5.1, when receiving a request for the /foo
URL, Symfony will
match the route2
because its priority is 10
(and the route1
priority
is the default 0
).
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
https://github.com/symfony/symfony/issues/18415
So I used the annotation "requirements" which I think is clearer than the "priority". When you or somebody else read your code you can see that the matching won't operate. Because it's in the regexp, not just a number. Priority might be easyer to write.
But it is still a good to know that thing can change!
@Christophe you are right. It feels better to add restrictions to routes to control the URL matching. However, sometimes (e.g. with catch-all routes) a priority is a much better solution (e.g. give the catch-all route a big negative priority and most of your problems will be solved).