Kevin Bond
Contributed by Kevin Bond in #45657 and #45783

Attributes are probably one of the new features in PHP that have the most positive impact on the way we develop applications. They add structured, machine-readable metadata information in code. In Symfony we added support for them in:

In Symfony 6.1 we're introducing another feature related to attributes so you can instruct the autowiring logic with PHP attributes.

By default, the autowiring logic reads the type-hints on your constructor (/setters) and that's enough to automate the resolution of most dependencies.

However, sometimes you may need another service than the default one, or you may need a scalar value, etc. In similar situations, you had to use explicit configuration in your config/services.yaml file.

Thanks to the new #[Autowire] attribute, you can now instruct the autowiring logic to replace the default rule by a more specific one in case you need so:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
use Symfony\Component\DependencyInjection\Attribute\Autowire;

class MyService
{
    public function __construct(
        #[Autowire(service: 'some_service')]
        private $service1,

        #[Autowire(expression: 'service("App\\Mail\\MailerConfiguration").getMailerMethod()')]
        private $service2,

        #[Autowire('%env(json:file:resolve:AUTH_FILE)%')]
        private $parameter1,

        #[Autowire('%kernel.project_dir%/config/dir')]
        private $parameter2,
    ) {}

    // ...
}
Published in #Living on the edge