Symfony 4在DI Extension类中加载和处理自定义Yaml配置文件

问题描述 投票:5回答:1

我正在尝试按照此处提供的文档在我的应用程序中导入yaml配置文件:http://symfony.com/doc/current/bundles/extension.html但我总是有错误消息:没有扩展程序可以加载“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;
    }
}

我无法访问我的参数:( 任何的想法 ?谢谢。

symfony yaml symfony4
1个回答
9
投票

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

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

希望这可以帮助。

© www.soinside.com 2019 - 2024. All rights reserved.