Fabien Potencier
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) { ... }
}
Published in #Living on the edge