使用Symfony配置树构建器创建多维数组

3
我希望创建一个自己的捆绑包配置,就像这样:
```html

我想创建一个自己的捆绑包配置,就像这样:

```
my_filters:
    filter_type_a:
        - \MyBundle\My\ClassA
        - \MyBundle\My\ClassA2
    filter_type_b:
        - \MyBundle\My\ClassB
my_filters 应该是一个长度可变的数组,my_filters.filter_type_a 也应该是一个长度可变的数组。
我尝试过了。
$treeBuilder = new TreeBuilder(); 
$rootNode = $treeBuilder->root('my_bundle');
$rootNode
     ->children()
         ->arrayNode('my_filters')
             ->prototype('array')
                 ->prototype('array')
                     ->children()
                         ->scalarNode('my_filters')->end()
                      ->end()
                 ->end()
             ->end()
         ->end()
     ->end()

但是我遇到了以下错误:"my_bundle.my_filters.filter_type_a.0"的路径类型无效。期望数组,但得到了字符串

这是我设置配置信息的地方:

class MyBundleExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        $this->loadServices($container);
        $this->loadConfig($configs, $container);
    }

    private function loadConfig(array $configs, ContainerBuilder $container)
    {       
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);
        $container->setParameter('my_bundle.my_filters', $config['my_filters']);
    }

    private function loadServices(ContainerBuilder $container)
    {
        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');
    }
}

我看不出我的错误,有人可以告诉我吗?

你的 rootNode 是什么?更改其中一个示例以使它们相互兼容。现在你已经定义了 filter_expressions,但是提供了 my_filtersfilter_type_a,这是不清楚的。 - Michael Sivolobov
抱歉,我忘记了。我已经将根节点添加到示例中。 - jagemue
我认为你的错误在于命名。你用一个名称my_filters声明了两个不同的节点。 - Michael Sivolobov
即使我更改内部标量节点的名称,错误仍然会出现。 - jagemue
1个回答

4
为匹配配置文件
my_bundle:
    my_filters:
        filter_type_a:
            - \MyBundle\My\ClassA
            - \MyBundle\My\ClassA2
        filter_type_b:
            - \MyBundle\My\ClassB

您需要在配置树构建器中添加以下代码:
$rootNode = $treeBuilder->root('my_bundle');
$rootNode
     ->children()
         ->arrayNode('my_filters')
             ->prototype('array')
                 ->prototype('scalar')->end()
             ->end()
         ->end()
     ->end()

好的,没有错误,但是参数'my_filters'为空,如果我尝试使用$container->getParameter('my_bundle.my_filters')读取它。 - jagemue
请发布整个类的代码。您确定在容器编译时调用了loadConfig吗? - Michael Sivolobov
是的,我已经删除了 app/cache/ 文件夹,但问题仍然存在。 - jagemue
如果我使用原始代码,我可以看到配置已被读取:ArrayNode->normalizeValue(array('my_filters' => array('filter_type_a' => array('\MyBundle\MyClassA')))) in BaseNode.php line 264,但Symfony告诉我它发现了一个“无效类型”(请参见我的问题)。 - jagemue
1
此答案应发布在官方Symfony文档中 ;) - Pinks Not Dead
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接