Injecting the Symfony project root directory in your services with a PHP attribute

Published on 2023-09-29 • Modified on 2023-09-29

In the previous snippet, we saw how to inject the Symfony project root directory in the services with a bind. We can also use a PHP attribute. This new feature is available as of Symfony 6.1. Which one do you prefer? For this particular case, I find the bind more convenient to use.


<?php

declare(strict_types=1);

use Symfony\Component\DependencyInjection\Attribute\Autowire;

final class fooBarService
{
    public function __construct(
        #[Autowire('%kernel.project_dir%')]
        private $projectDir
    ) {}
}

 More on Stackoverflow   Read the doc  Random snippet

  Work with me!