New in Symfony 3.4: Prefix all controller route names

Contributed by
Fabien Potencier
in #24031.

In Symfony applications, the class of a controller can define the @Route annotation to set a common prefix for the URLs used by the action methods:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

/**
 * @Route("/blog")
 */
class BlogController extends Controller
{
    /**
     * @Route("/", defaults={"page": "1"}, name="blog_index")
     * @Route("/page/{page}", name="blog_index_paginated")
     */
    public function indexAction($page, $_format) { ... }

    /**
     * @Route("/posts/{slug}", name="blog_post")
     */
    public function showAction(Post $post) { ... }
}

In this example, the URL of the index action will be /blog/ and /blog/page/... and the URL of the show action will be /blog/posts/....

As you can see in this example, it's also a common practice to use a consistent naming for the routes of a single controller (blog_index, blog_post, etc.) That's why in Symfony 3.4, we improved the @Route() annotation to also allow defining the common part of the controller route names.

Add a name property to the @Route annotation of the controller class and that will be considered the prefix of all route names. The following is equivalent to the previous example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

/**
 * @Route("/blog", name="blog_")
 */
class BlogController extends Controller
{
    /**
     * @Route("/", defaults={"page": "1"}, name="index")
     * @Route("/page/{page}", name="index_paginated")
     */
    public function indexAction($page, $_format) { ... }

    /**
     * @Route("/posts/{slug}", name="post")
     */
    public function showAction(Post $post) { ... }
}

Comments

Great ! :-)
Is it possible to use the route name without prefix?
If yes, where? How to avoid confusions?
Thanks!
@Ionuț I'm not sure if I understand your question. To not add a prefix to your route names, you just need to not add the "name" property to the @Route annotation of the whole class.
@Javier, I was thinking of path() templates and generateUrl() in controllers...

Would be interesting if we can skip the prefix when calling generateUrl() in the same controller.

Not sure about path() in templates...
I understand you now :) Yeah, it's not possible to skip the prefix when generating routes. It would look and feel a bit "magical". I guess it's better to be explicit in those cases, even if you need to type a bit more.
Cool!
But, from a twig file, will the IDE be able to take you to the route definition?
@Raúl to follow IDE / PhpStorm implementation see https://github.com/Haehnchen/idea-php-symfony2-plugin/issues/1017
Great ! :-)
Great!
Can't wait to try it out!
This is really nice to have! Great job !!
Nice :) !!!
Why not.
Really cool !
Login with SensioLabsConnect to post a comment