如何在 DI Extension class 中加载、处理和使用来自 Yaml 配置文件的自定义参数?

How to load, process and use custom parameters from Yaml configuration files in DI Extension class?

我正在尝试按照此处提供的文档在我的应用程序中导入一个 yaml 配置文件 http://symfony.com/doc/current/bundles/extension.html,但我总是收到错误消息:

There is no extension able to load the configuration for "app"

我的文件位于此处:config/packages/app.yaml 并具有以下结构:

app:  
    list:  
        model1:  
            prop1: value1
            prop2: value2  
        model2:
            ...

由于这是一个简单的应用程序,所有文件都在src/中。所以我有 src/DependencyInjection/AppExtension.php

<?php

namespace App\DependencyInjection;

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

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

src/DependencyInjection/Configuration.php

<?php

namespace App\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('app');

        // Node definition
        $rootNode
            ->children()
                ->arrayNode('list')
                    ->useAttributeAsKey('name')
                    ->requiresAtLeastOneElement()
                    ->prototype('array')
                        ->children()
                            ->requiresAtLeastOneElement()
                            ->prototype('scalar')
                            ->end()
                        ->end()
                    ->end()
                ->end()
            ->end();

        return $treeBuilder;
    }
}

我无法访问我的参数:(
有什么想法吗?

如果您想加载自定义配置文件以使用扩展 class 处理它的参数(类似于 Symfony 捆绑扩展但不创建捆绑),最终 "create" 并将其中的一个或多个添加到 "container" ( 在它被编译之前 )你可以手动注册你的扩展 class Kernel.php 文件中包含的 configureContainer 方法:

protected function configureContainer(ContainerBuilder $container, LoaderInterface $loader)
{
    // to avoid the same error you need to put this line at the top
    // if your file is stored under "$this->getProjectDir().'/config'" directory
    $container->registerExtension(new YourAppExtensionClass());

    // ----- rest of the code
}

然后你可以像往常一样使用你的参数registering a Compiler Pass

希望对您有所帮助。