New in Symfony 6.4: FQCN-based Routes
Contributed by
Thomas Calvet
in #50084.
In Symfony applications, the routing system requires each route to have a name,
which is an arbitrary string that uniquely identifies the route. This name is
later used for example when generating URLs based on route definitions.
The route name is usually defined explicitly by developers when adding routes
(e.g. via the name option of the #[Route] attribute):
namespace AppController;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentRoutingAnnotationRoute;
final class BlogController extends AbstractController
{
#[Route(‚/blog‘, name: ‚blog_index‘)]
public function index(): Response
{
// …
}
}
If you don’t define the route name explicitly, Symfony generates an automatic
route name based on the namespace of the controller and the action method name.
In the above example, the automatic route name would be app_blog_index.
In some Symfony applications, developers use invokable controllers to define just
one action per controller. For example:
namespace AppController;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentRoutingAnnotationRoute;
#[Route(‚/blog‘)]
final class BlogController extends AbstractController
{
public function __invoke(): Response
{
// …
}
}
Given that the controller only defines a single route, the FQCN (fully-qualified
class name) of the controller can uniquely identify that route. That’s why in
Symfony 6.4, we’re introducing automatic route names based on controllers‘ FQCN.
In practice, the above example will now define a route called AppControllerBlogController,
so you can generate URLs based on that route as follows:
use AppControllerBlogController;
// …
$url = $this->urlGenerator->generate(BlogController::class);
In addition to invokable controllers, this feature also works for controllers
that only define a single route. In the following example, the generated route
name is AppControllerBlogController::index:
namespace AppController;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentRoutingAnnotationRoute;
final class BlogController extends AbstractController
{
#[Route(‚/blog‘)]
public function index(): Response
{
// …
}
}
This feature is completely optional, so you can keep using and defining routes
as you always did. However, this will allow developers using invokable and
single-route controllers to avoid using „magic strings“ to define route names.
Symfony Blog