<service id="my_service">
<tag name="my_transport" supports="feature1, feature2, feature3" />
</service>
可以在处理 XML 配置时定义supports
属性,而不是执行?array
preg_split
<service id="my_service">
<tag name="my_transport" supports="feature1, feature2, feature3" />
</service>
可以在处理 XML 配置时定义supports
属性,而不是执行?array
preg_split
没有办法将属性定义为array
.
DependencyInjection 加载器不支持这一点。(例如,如果你尝试这个,从yml
抛出异常加载)A "tags" attribute must be of a scalar-type (...)
XmlFileLoader 加载标签使用phpize解析属性值为 null、布尔值、数字或字符串。
向服务定义添加标签不会覆盖之前添加的标签的定义,而是向数组添加新条目。
public function addTag($name, array $attributes = array())
{
$this->tags[$name][] = $attributes;
return $this;
}
所以你应该尝试创建多个<tag>
元素(如 Wouter J 所说)
如果你的 XML 文件会像
<service id="my_service">
<tag name="my_transport" supports="feature1" />
<tag name="my_transport" supports="feature2" />
<tag name="my_transport" supports="feature3" />
</service>
那么标签的 $attributesmy_transport
将是
Array
(
[0] => Array
(
[supports] => feature1
)
[1] => Array
(
[supports] => feature2
)
[2] => Array
(
[supports] => feature3
)
)
及样品用法
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
class MyCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$definition = $container->getDefinition('my_transport_service');
// Extensions must always be registered before everything else.
// For instance, global variable definitions must be registered
// afterward. If not, the globals from the extensions will never
// be registered.
$calls = $definition->getMethodCalls();
$definition->setMethodCalls(array());
foreach ($container->findTaggedServiceIds('my_transport') as $id => $attributes) {
// print_r($attributes);
foreach($attributes as $attrs)
{
switch($attrs['supports']){
case 'feature1':
$definition->addMethodCall('addTransportFeature1', array(new Reference($id)));
break;
case 'feature2':
$definition->addMethodCall('addTransportFeature2', array(new Reference($id)));
break;
case 'feature3':
$definition->addMethodCall('addTransportFeature3', array(new Reference($id)));
break;
}
}
}
$definition->setMethodCalls(array_merge($definition->getMethodCalls(), $calls));
}
}