2016-01-21 97 views
0

使用CompilerPass,我需要将setter添加到所有继承特定抽象类的服务。 它们已被标记,但只有一些使用抽象类。Symfony DependencyInjection - 如何获得某种类型的所有服务?

类似的东西:

$abstractServices = $containerBuilder->findServicesByType('MyAbstractClass'); 

$abstractServices->addMethodCall(
    'setHelperService', 
    [new Reference('@service_to_be_set') 
); 

什么你有什么建议?

+0

您是否尝试过使用抽象服务?在这种情况下,你可以定义只在你的父服务中的所有子服务的集合将继承此 –

+0

你能链接到我吗? –

回答

1

您可以简单地检查服务类是否是指定抽象类的子类。

foreach ($container->getDefinitions() as $definition) { 
    if (is_subclass_of($definition->getClass(), 'YourAbstractClass')) { 
     // do something 
    } 
} 
+0

你在练习中使用这个吗? –

+0

否。查看抽象服务。 –

+0

你能分享一些链接吗?谷歌给了一些各种随机来源。 –

1

基于托马斯的回答

$taggedServices = $container->findTaggedServiceIds('your_tag'); 

foreach ($taggedServices as $id => $tags) { 
    $service = $container->findDefinition($id); 
    if (!is_callable($service, 'yourMethodName') { 
     continue; 
     // or raise exception if you need 
    } 
    $service->addMethodCall(...); //whatever 
} 

另一种方式是

$taggedServices = $container->findTaggedServiceIds('your_tag'); 

foreach ($taggedServices as $id => $tags) { 
    $service = $container->findDefinition($id); 
    if (!$service instance YourInterface) { 
     continue; 
     // or raise exception if you need 
    } 
    $service->addMethodCall(...); //whatever 
} 

当然事件是基于标签和只用实例或抽象类(如果方法您正在搜索的工作原理在后一种情况下是抽象的)

+0

这是有点解决方法,但似乎是迄今为止最好的。谢谢。你能想到其他不使用标签的东西吗? –

+0

@TomášVotruba如果Tomasz没有回答,我会回答相同的,所以不,我认为是最好的方法:) – DonCallisto

+0

我不会认为这是一个解决方法,答案似乎是一个完全合法的方式来做你的正在做。 –

相关问题