New in Symfony 6.1: Service Autowiring Attributes
May 3, 2022 • Published by Javier Eguiluz
Symfony 6.1 is backed by:
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
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:
- New in Symfony 5.2: Routing PHP attributes
- New in Symfony 5.2: Constraints as PHP attributes
- New in Symfony 5.2: Controller argument attributes
- New in Symfony 5.3: Service Autoconfiguration attributes
- New in Symfony 5.3: Autowiring Iterators/Locators and Aliases with Attributes
- New in Symfony 6.1: Service Decoration Attributes
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,
) {}
// ...
}
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
That would be a nice addition too.
New in Symfony 5.3: Service Autowiring with Attributes
https://symfony.com/blog/new-in-symfony-5-3-service-autowiring-with-attributes
Even a very simple '%env(string:MY_ENV_VAR)%' returns an error saying "The paramter must be defined."