【问题标题】:Exactly how does the defaultValue work in Symfony 2.0 NodeDefinition?在 Symfony 2.0 NodeDefinition 中 defaultValue 究竟是如何工作的?
【发布时间】:2012-05-05 01:25:14
【问题描述】:

我试图在 Symfony 2.0 的包中公开语义配置,但我无法让 defaultValue 在 NodeDefinition 类中工作。我生成了一个空包并为配置工作创建了必要的文件,并且我能够获取配置值,但我想将 defaultValue 设置为配置项。我使用 defaultValue() 方法并从我的 config.yml 中删除配置项,然后它显示一个空数组?谁能解释一下 defaultValue() 的实际工作原理,我错过了什么吗?

<?php
// ./DependencyInjection/Configuration.php

namespace Test\Bundle\TestBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class Configuration implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('test_bundle');

        $rootNode
            ->children()
                ->scalarNode('foo')->defaultValue('bar')->end()
            ->end();

        return $treeBuilder;
    }
}

-

<?php
// ./DependencyInjection/TestBundleExtension.php

namespace Test\Bundle\TestBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

class TestBundleExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        var_dump($configs); // empty array

        $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.xml');
    }
}

所以从上面的配置类中,当配置项'test_bundle.foo'丢失时,它的值肯定会设置为'bar'......是吗?嗯,这就是我的想法,但事实并非如此。

【问题讨论】:

    标签: php configuration symfony


    【解决方案1】:

    您的根节点是一个数组节点。默认情况下,如果您不设置键,则不应用默认值。 2 个关于如何使默认值起作用的示例:

    1. 将值设置为空:

      # in the config.yml
      test_bundle:
          foo: ~
      
    2. 如果没有设置,告诉你的根节点使用默认值:

      // in your Configuration.php
      $rootNode
          ->addDefaultsIfNotSet()
          ->children()
              ->scalarNode('foo')->defaultValue('bar')->end()
          ->end();
      
      # in the config.yml
      test_bundle: ~
      

    【讨论】:

    • 示例 #1 不起作用,它将 null 视为它的值。但是示例 #2 有效,因此如果您缺少密钥,配置将添加它并将其设置为默认值。谢谢 JF 西蒙!!
    • 例如 #1 可以使用 API 文档中的treatNullLike。
    猜你喜欢
    • 2023-04-01
    • 2011-06-26
    • 2021-08-15
    • 2012-06-08
    • 2011-10-11
    • 2013-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多