Symfony AutoWire multiple services same class
Starting with 4.2, you can define named autowiring aliases. That should work:
services: Namespace\MyClass $serviceA: '@service.a' Namespace\MyClass $serviceB: '@service.b'
With Symfony 3.4 and 4.1, you can use bindings instead - but that's less specific as that doesn't take the type into account:
services: _defaults: bind: $serviceA: '@service.a' $serviceB: '@service.b'
Another options is to implement the Factory Pattern. This pattern will enable you to create a service based on the arguments provided.
# services.ymlservice.a: class: App\MyClass factory: 'App\Factory\StaticMyClassFactory:createMyClass' arguments: - ['argument1']service.b: class: App\MyClass factory: 'App\Factory\StaticMyClassFactory:createMyClass' arguments: - ['argument2']
And your StaticMyClassFactory would look like this
class StaticMyClassFactory{ public static function createMyClass($argument) { // Return your class based on the argument passed $myClass = new MyClass($argument); return $myClass; }}
You can still use the "@servicename" in the service.yml files, and so wire them by name/ Here's an example where I have a couple of different Loggers being wired into a service constructor.
# App/Subscribers/WebhookLoggingListener.php filepublic function __construct( LoggerInterface $logger, LoggerInterface $mailgunLog{ }# services.ymlApp\Subscribers\WebhookLoggingListener: arguments: $logger: "@logger" $mailgunLog: "@monolog.logger.mailgun" tags: - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest
You can also bind them to variable names (in the services: _defaults:
at the head of a services.yaml file, but if they won't be reused, I consider it better to keep the configuration more localised).