【发布时间】:2015-02-18 18:55:47
【问题描述】:
我在捆绑扩展中定义了一些配置:
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$loader->load('services.yml');
if (!empty($config['my_config'])) {
$my_config = $config['my_config'];
if (is_array($my_config)) {
$service_definition = $container->getDefinition('my_service');
foreach ($my_config as $name => $class) {
$reflection_class = new \ReflectionClass($class);
if (!$reflection_class->implementsInterface('MyInterface')) {
throw new \Exception(
"'$class' must implement MyInterface'"
);
}
$service_definition->addMethodCall('addElement', array($name, $class));
}
}
}
}
然后在MyService 我有:
public function addElement($name, $class_name) {
$this->elements[$name] = new $class_name();
}
所有这些元素都实现了MyInterface,一切都很好,直到我有了对其他服务或参数有一些依赖关系的新元素。这些新类可以定义为从 DI 中受益的服务。但是现在我需要重写MyExtension和MyService来满足新的需求。
如何在以这种方式调用的 setter 注入中从容器中获取服务?
【问题讨论】:
-
我认为依赖注入的标签系统对你有用,这里是文档symfony.com/doc/current/components/dependency_injection/…
-
谢谢。您的解决方案很棒,但如果我有大约 100 个 POPO,我不想为每个对象注册服务。
标签: php symfony dependency-injection