如何使用Symfony Config作为独立组件将导入的配置与环境配置合并?

时间:2018-01-10 13:37:03

标签: php symfony

我将symfony/config(v3.3)作为独立组件集成到遗留项目中。

一切顺利,但配置处理器不会将继承/导入的配置config.yml与环境配置config_<ENV>.yml合并(正如我所料)。

在调用$container->getExtensionConfig('whatever_node')时,而不是获得合并配置,结果数组包含两个配置。

编辑1

事实证明,导入parameters.yml以替换配置参数也不起作用(即在配置文件中使用%parameter_key%)。

编辑2

以下是有关dev环境的完整配置示例:

# parameters.yml
parameters:
    app_some_parameter_1: 'Some value for parameter 1'
    app_some_parameter_2: 'Another value for that second parameter'
# config.yml
imports:
    - { resource: parameters.yml }

app:
    some_parameter_1: '%app_some_parameter_1%'
    some_parameter_2: '%app_some_parameter_2%'
# config_dev.yml
imports:
    - { resource: config.yml }

app:
    some_parameter_2: 'Parameter 2 value in the dev environment'

最终的预期配置:

[
    "some_parameter_1" => "Some value for parameter 1",
    "some_parameter_2" => "Parameter 2 value in the dev environment"
]

我得到了什么:

[
  [
    "some_parameter_1" => "%app_some_parameter_1%",
    "some_parameter_2" => "%app_some_parameter_2%"
  ],
  [
    "some_parameter_2" => "Parameter 2 value in the dev environment"
  ]
]

1 个答案:

答案 0 :(得分:0)

实际上,从容器中检索到的数组ExtensionConfig(我在这里谈论的是#34;仿真&#34;容器而不是由通用Symfony应用程序构建的容器)不是尚未处理。

要获得最终的合并配置,您需要使用自己的扩展和配置来处理它:

# Acme/DependencyInjection/AcmeExtension.php
namespace Acme\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

class AcmeExtension extends Extension
{
    /**
     * @param array $configs
     * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container
     *
     * @return array
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $resolvedConfigs = [];

        foreach ($configs as $config) {
            $resolvedConfigs[] = $container->getParameterBag()->resolveValue($config);
        }

        return $this->processConfiguration(new Configuration(), $resolvedConfigs);
    }
}
# Acme/DependencyInjection/Configuration.php
namespace Acme\DependencyInjection;

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

class Configuration implements ConfigurationInterface
{
    /**
     * @return \Symfony\Component\Config\Definition\Builder\TreeBuilder
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('acme');

        $rootNode
            ->children()
                # ...
            ->end()
        ;

        return $treeBuilder;
    }
}