是否可以在 Symfony2 中动态注册包? [英] Is it possible to dynamically register bundles in Symfony2?

查看:21
本文介绍了是否可以在 Symfony2 中动态注册包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个加载器包 (LoaderBundle),它应该在同一目录中注册其他包.

I have a loader bundle (LoaderBundle) that should register other bundles in the same directory.

/Acme/LoaderBundle/...
/Acme/ToBeLoadedBundle1/...
/Acme/ToBeLoadedBundle2/...

我想避免在 AppKernel::registerBundles() 中手动注册每个新包(在 Acme 目录中).最好我希望 LoaderBundle 中的某些东西在每个请求上运行并动态注册 ToBeLoadedBundle1ToBeLoadedBundle2.可能吗?

I'd like to avoid manually registering every new bundle (in Acme directory) in AppKernel::registerBundles(). Preferably I'd like something in LoaderBundle to run on every single request and dynamically register ToBeLoadedBundle1 and ToBeLoadedBundle2. Is it possible?

推荐答案

未经测试,但你可以尝试类似的东西

Untested but you could try something like

use SymfonyComponentHttpKernelKernel;
use SymfonyComponentConfigLoaderLoaderInterface;
use SymfonyComponentFinderFinder;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            new SymfonyBundleFrameworkBundleFrameworkBundle(),
            //... default bundles
        );

        if (in_array($this->getEnvironment(), array('dev', 'test'))) {
            $bundles[] = new SymfonyBundleWebProfilerBundleWebProfilerBundle();
            // ... debug and development bundles
        }

        $searchPath = __DIR__.'/../src';
        $finder     = new Finder();
        $finder->files()
               ->in($searchPath)
               ->name('*Bundle.php');

        foreach ($finder as $file) {
            $path       = substr($file->getRealpath(), strlen($searchPath) + 1, -4);
            $parts      = explode('/', $path);
            $class      = array_pop($parts);
            $namespace  = implode('\', $parts);
            $class      = $namespace.'\'.$class;
            $bundles[]  = new $class();
        }

        return $bundles;
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
    }
}

这篇关于是否可以在 Symfony2 中动态注册包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆