如何为一个Bundle创造友好的配置

###使用Bundle扩展类php

在app/config/config.yml中为本身bundle配置参数
acme_demo:#这个为须要配置bundle的别名
    demo:
        client_id: 123
        client_secret: xxxx

在上一篇如何加载服务中讲到如何建立一个扩展类;在扩展类中处理这些配置参数数组

在load()方法中symfony自动会把YML或XML格式的配置参数转换成数组了app

array(
    // values from config.yml
    array(
        'demo' => array(
            'client_id' => 123,
            'client_secret' => xxx,
        ),
    ),
    // values from config_dev.yml
    array(
        'demo' => array(
            'client_id' => 456,
        ),
    ),
)

须要注意这是一个多维数组;各类环境下加载的配置不同;ui

symfony提供了方法可以让根据环境不一样选择不一样的参数并且还能够验证参数的正确性this

####添加配置类spa

// src/Acme/DemoBundle/DependencyInjection/Configuration.php
namespace Acme\DemoBundle\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('acme_social');

        $rootNode
            ->children()
                ->arrayNode('demo')
                    ->children()
                        ->integerNode('client_id')->end()#整形节点
                        ->scalarNode('client_secret')->end()#标量类型
                    ->end()
                ->end() // twitter
            ->end()
        ;

        return $treeBuilder;
    }
}

在load()方法中验证以及合并配置.net

public function load(array $configs, ContainerBuilder $container)
{
    $configuration = new Configuration();

    $config = $this->processConfiguration($configuration, $configs);
    // ...
}

能够让扩展类继承ConfigurableExtension来减小每次都要调用processConfiguration方法来验证合并配置scala

class Test2Extension extends ConfigurableExtension
{
    //注意这个方法名称不是load;
    protected function loadInternal(array $mergedConfig, ContainerBuilder $container)
    {
        // ...
    }
}
相关文章
相关标签/搜索