New in Symfony 5.4: DependencyInjection Improvements (Symfony Blog)


Symfony 5.4
is backed by Private Packagist. Private Packagist is a fast, reliable, and secure Composer repository for your private packages. It mirrors all your open-source dependencies for better availability and monitors them for security vulnerabilities.

In Symfony 5.4 you can use tagged iterators as arguments of service locators,
which simplifies the injection of tagged services in other services. The following
example shows how to use this feature when using YAML config (it works with XML
and PHP config too):

PHP 8.0 added union types (e.g. ClassA | ClassB $variable) and PHP 8.1 adds
intersection types (ClassA & ClassB $variable). In Symfony 5.4 we’ve improved
the DependencyInjection component to support both. For example:

Autowiring of intersection types works when both types have a corresponding
autowiring alias, and if both aliases point to the very same service.

In previous Symfony versions, the ServiceSubscriberTrait could be used to
inject services in some of your class methods. This trait looks for all methods
in your class that have no arguments and a return type to provide a
ServiceLocator for the services of those return types.

This behavior works well most of the times, but in some cases it’s common to
have such a method (no arguments but a return type) which shouldn’t get any
services injected. That’s why in Symfony 5.4 we’ve deprecated that behavior
and introduced a new SubscribedService PHP attribute.

Add that attribute to any method in which you want a service injected:

In Symfony you can autoconfigure classes annotated with attributes using some
code like the following in your dependency injection extension:

In Symfony 5.4 we’ve improved this feature to allow you to also autoconfigure
methods, properties and parameters. First, make sure that you have some PHP
attribute defined in your application that allows using them on methods and properties.

Now, use that PHP attribute in some method and/or property:

You can now use the registerAttributeForAutoconfiguration() method in your
extension, together with a union of the types that you want to search for.
In this example, the extension only cares for classes and methods, so it uses
ReflectionClass|ReflectionMethod $reflector:



Source link

Latest articles

Related articles

Leave a reply

Please enter your comment!
Please enter your name here