我想配置一个bundle,允许不同的公司有不同的行为。它们中的配置结构将是相同的。
我的config.yml
应该是这样的:
bunde_namespace:
company:
company_1:
foo: bar
baz: poit
company_2:
foo: bar
baz: poit
company_3:
...
当我访问$config
时,我希望数组看起来像这样:
$config['company'] = [
'company_one' => [
'foo' => 'bar'
'baz' => 'poit'
],
'company_two' => [
'foo' => 'bar'
'baz' => 'poit'
],
...
];
然而,我没有经验与TreeBuilder和设置配置的文档中所描述的,它仍然逃避我,我如何设置我的配置,以便它对待company
的子键数组。
到目前为止,我完成的是为一个公司设置配置,如下所示:
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('dreamlines_booking_service_fibos');
$rootNode
->children()
->arrayNode('company')
->children()
->scalarNode('foo')->end()
->scalarNode('baz')->end()
->end()
->end()
->end();
return $treeBuilder;
}
}
简化后的config.yml
是这样的:
bundle_namespace:
company:
foo: bar
baz: poit
但这不是我想要的。
我假设我需要使用useAttributeAsKey
,但我有困难让它工作。
这失败:
$rootNode
->children()
->arrayNode('company')
->prototype('array')
->useAttributeAsKey('name')
->children()
->scalarNode('foo')->end()
->scalarNode('baz')->end()
->end()
->end()
->end()
->end();
声明:
' Config '定义' [Symfony '组件异常' InvalidDefinitionException]->useAttributeAsKey()不适用于路径"bundle_namespace"下的具体节点。"
我哪里错了?
当您尝试在原型上应用useAttributeAsKey
时,您会得到错误,但由于该方法是ArrayNodeDefinition的一部分,因此需要在->arrayNode(...)
之后添加它。试试这个方法,错误就会消失。
现在,如果我正确理解了你的问题,下面的输出是你的目标:
Array
(
[company] => Array
(
[company_1] => Array
(
[foo] => bar
[baz] => baz
)
[company_2] => Array
(
[foo] => bar
[baz] => baz
)
)
)
,你可以通过下面的结构来实现:
$rootNode
->children()
->arrayNode('company')
->prototype('array')
->children()
->scalarNode('foo')->end()
->scalarNode('baz')->end()
->end()
->end()
->end()
->end()
;
加载的配置:
app:
company:
company_1:
foo: bar
baz: baz
company_2:
foo: bar
baz: baz
如果我误解了你的问题,请附上评论