1

我正在尝试在包中加载自定义 YAML 配置文件,该文件出错,说:

没有扩展能够加载配置


自定义 YAML 配置文件:

#AppBundle/Resources/config/myconfig.yml
myapp: myvalue

配置文件:

//AppBundle/DependencyInjection/MyConfiguration.php

namespace AppBundle\DependencyInjection;

use ...

class MyConfiguration implements ConfigurationInterface {

    public function getConfigTreeBuilder() {
        $treeBuilder = new TreeBuilder();
        $treeBuilder->root('myapp')->end();

        return $treeBuilder;
    }

}

扩展文件:

//AppBundle/DependencyInjection/AppExtension.php

namespace AppBundle\DependencyInjection;

use ...

class AppExtension extends Extension {

    public function load(array $configs, ContainerBuilder $container)
    {
        $this->processConfiguration(new MyConfiguration(), $configs);

        $loader = new YamlFileLoader(
            $container,
            new FileLocator(__DIR__.'/../Resources/config')
        );

        $loader->load('myconfig.yml');
    }   

}

完整的错误信息:

YamlFileLoader.php 第 399 行中的 InvalidArgumentException:没有扩展能够加载“myapp”的配置(在 C:\my_project\src\AppBundle\DependencyInjection/../Resources/config\myconfig.yml 中)。寻找命名空间“myapp”,没有找到


4

1 回答 1

1

这是因为您使用myapp自定义别名。

第一种解决方案:使用默认别名

Symfony 默认使用下划线版本的包名称(例如AcmeTestBundle将转换为acme_test)。

考虑到您的捆绑名称空间,app别名将是默认值。

您可以更改此代码:

$treeBuilder->root('myapp')->end();

进入这个:

$treeBuilder->root('app')->end();

然后使用app配置文件中的密钥。

这是首选解决方案,因为它使您的配置与您的包名称匹配。如果配置名称不适合您,可能是因为包的名称不正确!

替代解决方案:保留您的自定义别名

您的应用程序中可能只有一个捆绑包,之所以调用它是AppBundle因为您不打算在任何其他项目中重用此捆绑包。如果您仍想使用自定义别名(myapp而不是app),可以采用以下方法:

<?php
//AppBundle/DependencyInjection/AppExtension.php

namespace AppBundle\DependencyInjection;

use ...

class AppExtension extends Extension {

    public function load(array $configs, ContainerBuilder $container)
    {
        // ...
    }


    public function getAlias()
    {
        return 'myapp';
    }
}

因为 Symfony 默认不喜欢这个别名,所以也改变你的 Bundle 文件:

<?php
// AppBundle/AppBundle.php
namespace AppBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;

class AppBundle extends Bundle
{
    /**
     * {@inheritdoc}
     */
    public function getContainerExtension()
    {
        if (null === $this->extension) {
            $extension = $this->createContainerExtension();

            if (null !== $extension) {
                if (!$extension instanceof ExtensionInterface) {
                    throw new \LogicException(sprintf('Extension %s must implement Symfony\Component\DependencyInjection\Extension\ExtensionInterface.', get_class($extension)));
                }

                $this->extension = $extension;
            } else {
                $this->extension = false;
            }
        }

        if ($this->extension) {
            return $this->extension;
        }
    }
}
于 2016-05-25T08:42:46.750 回答