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,
) {}
// ...
}
Love this! I constantly forget changing some param in some config and cursing about yaml. Having this right next to the relevant code will make it much easier :-).
This is awesome, never ever gonna write YAML again \o/
One note though: after some tests,
!tagged_iterator
does not seem to be supported in the attribute. That would be a nice addition too.@Thibault for "tagged iterators", check this:
New in Symfony 5.3: Service Autowiring with Attributes https://symfony.com/blog/new-in-symfony-5-3-service-autowiring-with-attributes
How did I missed this!? Thanks @Javier
The example shows using '%env(json:file:resolve:AUTH_FILE)%', but I couldn't get that to work at all.
Even a very simple '%env(string:MY_ENV_VAR)%' returns an error saying "The paramter must be defined."
Good catch @Andrew, see https://github.com/symfony/symfony/pull/46272 for the fix.