New in Symfony 4.2: Autowiring by type and name
Contributed by
Nicolas Grekas
in #28234.
In modern Symfony applications, thanks to service autowiring and service autoconfiguration, there's no need to configure most (or any) of your services. However, in some edge-cases you may need to tell Symfony which exact service should be injected into other services.
This is solved with local binding which allows to bind services by type or name. For example, if you use YAML to configure services:
1 2 3 4 5 6 7 8 9 10 11 | # config/services.yaml
services:
_defaults:
bind:
# pass this value to any $adminEmail argument for any service
# that's defined in this file (including controller arguments)
$adminEmail: '[email protected]'
# pass this service for any LoggerInterface type-hint for any
# service that's defined in this file
Psr\Log\LoggerInterface: '@monolog.logger.request'
|
In Symfony 4.2 we've improved this feature to allow binding services by type and name at the same time. This new feature allows a more precise binding because it only applies when both the argument type and the argument name match.
1 2 3 4 5 6 7 8 9 | # config/services.yaml
services:
_defaults:
bind:
# it works with scalar types too (string, int, array, etc.)
string $adminEmail: '[email protected]'
# but it's mostly used with classes
Psr\Log\LoggerInterface $requestLogger: '@monolog.logger.request'
|
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.
New in Symfony 4.2: Autowiring by type and name symfony.com/blog/new-in-symfony-4-2-autowiring-by-type-and-name
Tweet thisComments
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
Roland Franssen said on Sep 20, 2018 at 09:13 #1