Define Route Alias in Symfony 8

Define Route Alias in Symfony 8

When maintaining a Symfony application over time, route names often change. Changing a route name can be risky because existing code, templates, or external integrations may still rely on the old name. Symfony solves this problem by allowing route aliases. This tutorial demonstrates how to define route alias in Symfony 8 application.

A route alias lets to assign additional names to an existing route. All aliases point to the same route definition, meaning no duplicated configuration and no duplicated controller logic. This is especially useful for backward compatibility or gradual refactoring.

The route alias can be defined with alias option. In the following example timestamp_now is the main route name. The timestamp_index is an alternative name that points to the same route. Both names reference the same URL and controller action.

src/Controller/TimestampController.php

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class TimestampController extends AbstractController
{
    #[Route('/now', name: 'timestamp_now', alias: ['timestamp_index'])]
    public function now(): Response
    {
        return new Response((string) time());
    }
}

config/routes.yaml

timestamp_now:
    path: /now
    controller: App\Controller\TimestampController::now

timestamp_index:
    alias: timestamp_now

To confirm that both route names behave identically, we can generate URLs for each and compare them.

src/Controller/TestController.php

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class TestController extends AbstractController
{
    #[Route('/test')]
    public function index(): Response
    {
        $url1 = $this->generateUrl('timestamp_now');
        $url2 = $this->generateUrl('timestamp_index');

        return new Response((string) ($url1 === $url2)); // 1
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.