我想配置一个 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 和 setting up the configuration as described in the docs 的经验我仍然不知道如何设置我的配置,以便将 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();
声明:
[Symfony\Component\Config\Definition\Exception\InvalidDefinitionException] ->useAttributeAsKey() is not applicable to concrete nodes at path "bundle_namespace."
我哪里出错了?
最佳答案
您收到的错误是当您尝试在原型(prototype)上应用 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
如果我误解了您的问题,请发表评论。
关于php - 如何使用TreeBuilder定义动态配置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33288144/