Symfony依赖注入将类型的所有类作为参数注入

时间:2019-01-06 21:06:59

标签: php symfony dependency-injection

如何告诉DI容器将某种类型的所有服务注入另一种服务?我想避免必须手动将所有这些服务注册为参数。

有什么方法可以自动化吗?

class A {

    /**
     * @var ISomeInterface[]
     */
    private $implementations;


    public function __construct(ISomeInterface ...$implementations)
    {
        $this->implementations = $implementations;
    }

}

interface ISomeInterface {}

1 个答案:

答案 0 :(得分:0)

这可以给您一个大致的想法。它更多是伪代码,因此请勿复制和粘贴。 Symfony允许您通过ContainerBuilder自定义服务的DI-在3.4中,我们在* Extension类中进行此操作。在您的应用中,您可以在有权访问容器构建器的任何地方进行操作。如果您知道需要注入哪些服务,则可以将其作为参考;如果不需要,则可以遍历定义并查找符合您的条件(即所需接口)的服务。

// 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);

    }
}

您可以使用$container->setArguments([/*your arguments*/])向服务中插入参数。

// 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');
    }