我试图在 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'......是吗?好吧,这就是我的想法,但事实并非如此。