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

2024-04-09

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

没有扩展能够加载“app”的配置

我的文件位于这里:配置/包/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);
    }
}

And 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 捆绑包扩展,但无需创建捆绑包),最终“创建”并将其中一个或多个添加到“容器”中(在编译之前)您可以在中手动注册您的扩展类configureContainer方法包含在Kernel.php file:

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
}

然后你可以像往常一样使用你的参数注册编译器通行证 https://symfony.com/doc/current/service_container/compiler_passes.html.

希望这可以帮助。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 DI 扩展类中加载、处理和使用 Yaml 配置文件中的自定义参数? 的相关文章

随机推荐