New in Symfony 3.4: Prefix all controller route names

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
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) { ... }
}
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
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
If yes, where? How to avoid confusions?
Thanks!
Would be interesting if we can skip the prefix when calling generateUrl() in the same controller.
Not sure about path() in templates...
But, from a twig file, will the IDE be able to take you to the route definition?