defaultValue 在 Symfony 2.0 NodeDefinition 中究竟是如何工作的


Exactly how does the defaultValue work in Symfony 2.0 NodeDefinition?

我试图在Symfony 2.0的捆绑包中公开语义配置,但我无法让defaultValue在NodeDefinition类中工作。我生成了一个空捆绑包并创建了配置工作所需的文件,并且我能够获取配置值,但我想将默认值设置为配置项。我使用 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"......是的?嗯,这就是我的想法,但事实并非如此。

根节点是阵列节点。默认情况下,如果未设置键,则不应用默认值。有关如何使默认值正常工作的 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: ~