Skip to content

Instantly share code, notes, and snippets.

@GromNaN
Created May 22, 2025 08:31
Show Gist options
  • Save GromNaN/e4c5a34d34529171fe07a76618ba481b to your computer and use it in GitHub Desktop.
Save GromNaN/e4c5a34d34529171fe07a76618ba481b to your computer and use it in GitHub Desktop.
Enable controller service with #[Route] attribute in Symfony < 7.3

It's possible to backport into an older Symfony project the new feature for Symfony 7.3 that automatically register classes declaring #[Route] attribute for injection of services into the controller.

symfony/symfony#60081

You need to update your App\Kernel class to register the attribute autoconfiguration.

<?php
namespace App;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
use Symfony\Component\Routing\Attribute\Route;
class Kernel extends BaseKernel
{
use MicroKernelTrait;
public function build(ContainerBuilder $container): void
{
$container->registerAttributeForAutoconfiguration(Route::class, static function (ChildDefinition $definition, Route $attribute, \ReflectionClass|\ReflectionMethod $reflection): void {
$definition->addTag('controller.service_arguments');
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment