将内核访问到bundle扩展类中


Access kernel into a bundle extension class

我试图增强我的一个bundle Extension,它加载我的YAML配置文件,我必须访问内核类才能使用方法locateResource()

目标是加载资源文件而不使用:

__DIR__ . '/../Resources/config'

扩展类如下:

class InnovaPathExtension extends Extension
{
    /**
     * Base path to the config directory of the bundle
     * @var unknown
     */
    const CONFIG_PATH = '@InnovaPathBundle/Resources/config/';
    /**
     * List of needed config files
     * @var array
     */
    protected $filesToLoad = array (
        // Services
        'services/services.yml',
        'services/listeners.yml',
        'services/managers.yml',
        'services/controllers.yml',
        // Parameters
        'parameters.yml',
    );
    /**
     * @see 'Symfony'Component'DependencyInjection'Extension'ExtensionInterface::load()
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        foreach ($this->filesToLoad as $file) {
            // Check if resources exists
            try {
                $resource = static::CONFIG_PATH . $file;
                $filePath = $container->get('kernel')->locateResource($resource);
            } catch ('InvalidArgumentException $e) {
                throw new 'InvalidArgumentException(sprintf('Unable to load "%s"', $resource), 0, $e);
            }
            // TODO : Load resource
        }
        return $this;
    }
}

指令$container->get('kernel')引发异常"服务定义"内核"不存在。"

如果我检查所有在$container->getServiceIds()注册的服务,我发现的唯一服务是service_container

没问题,我拿到服务容器,用$container->get('service_container')->getServiceIds()检查服务。。。我只得到一个服务:service_container

我不明白为什么。。。是DI-CEPTION吗?

推荐的方法是:

use Symfony'Component'DependencyInjection'Loader'YamlFileLoader;
use Symfony'Component'Config'FileLocator;
public function load(array $configs, ContainerBuilder $container)
{
    $loader = new YamlFileLoader(
        $container,
        new FileLocator(__DIR__.'/../Resources/config')
    );
    foreach ($this->filesToLoad as $file) {
        $loader->load($file);
    }
}

不建议采用其他方式。

请参阅http://symfony.com/doc/current/cookbook/bundles/extension.html#loading-外部配置资源