我正在努力通过类别名称从注入的已标记服务组中获取特定服务。
这是一个示例:我标记实现DriverInterface为的所有服务app.driver并将其绑定到$drivers变量。
在其他一些服务中,我需要获取所有已标记app.driver并实例化的驱动程序,并且仅使用其中一些驱动程序。但是需要的驱动程序是动态的。
services.yml
_defaults:
autowire: true
autoconfigure: true
public: false
bind:
$drivers: [!tagged app.driver]
_instanceof:
DriverInterface:
tags: ['app.driver']
Run Code Online (Sandbox Code Playgroud)
其他一些服务:
/**
* @var iterable
*/
private $drivers;
/**
* @param iterable $drivers
*/
public function __construct(iterable $drivers)
{
$this->drivers = $drivers;
}
public function getDriverByClassName(string $className): DriverInterface
{
????????
}
Run Code Online (Sandbox Code Playgroud)
因此,将实现的服务DriverInterface注入到$this->driversparam中作为可迭代的结果。我只能foreach通过它们,但是所有服务都将被实例化。
是否有其他方法可以将这些服务注入,以通过类名从它们获得特定服务而无需实例化其他服务?
我知道有可能将那些驱动程序公开并改为使用容器,但是我想避免以其他方式将容器注入服务中。