Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

php - Is it possible to dynamically register bundles in Symfony2?

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

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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');
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...