How can I tell the DI container to inject all services of a certain type to another service? I would like to avoid having to register all of these services manually as an argument.
Any way how to automate this?
class A {
/**
* @var ISomeInterface[]
*/
private $implementations;
public function __construct(ISomeInterface ...$implementations)
{
$this->implementations = $implementations;
}
}
interface ISomeInterface {}
This could give you a general idea. It's more of a pseudo code so don't copy and paste it. Symfony allows you to custmize DI for your services through ContainerBuilder
- in 3.4, we do it in the *Extension class. In your app, you can do it wherever you have access to a container builder. If you know which services you need to inject, you can get them as a reference, if not, you can loop through definitions and find services that match your criteria, i.e. desired interface.
// Symfony 3.4
- `*Extension.php` class, usually found in DependencyInjection folder of a bundle
class BundleExtension extends Extension
{
/**
* @param array $configs
* @param ContainerBuilder $container
* @throws \Exception
*/
public function load(array $configs, ContainerBuilder $container)
{
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); // Your services
$loader->load('services.yml');
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$implementations = [];
// Get your implementations
$implementations[] = ...;
// You can either loop through config, get them as references (new Reference() ...), compare to interface predicate
$aService = (new Definition(A:class)) // This is the crucial part
->setArgument(0, $implementations);
$container->setDefinition(A::class, $aService);
}
}
You can use $container->setArguments([/*your arguments*/])
to inject arguments to your service.
// Symfony 4.2
// Kernel.php ...
protected function configureContainer(ContainerBuilder $container, LoaderInterface $loader)
{
$container->addResource(new FileResource($this->getProjectDir().'/config/bundles.php'));
$container->setParameter('container.dumper.inline_class_loader', true);
$confDir = $this->getProjectDir().'/config';
$arguments = [];
$services = [1, '2', 3, 4, 'def', 'abc']; // Your services
foreach ($services as $item) {
if (gettype($item) === 'string') { // Check if they pass your criteria, this is just an example
$arguments[] = $item;
}
}
$aService = (new Definition(A::class, $arguments)); // Service definition
$container->setDefinition(A::class, $aService); // Inject it to a container
$loader->load($confDir.'/{packages}/*'.self::CONFIG_EXTS, 'glob');
$loader->load($confDir.'/{packages}/'.$this->environment.'/**/*'.self::CONFIG_EXTS, 'glob');
$loader->load($confDir.'/{services}'.self::CONFIG_EXTS, 'glob');
$loader->load($confDir.'/{services}_'.$this->environment.self::CONFIG_EXTS, 'glob');
}