Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to dynamically register bundles in Symfony2?

Tags:

php

symfony

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?

like image 550
Ondrej Slinták Avatar asked Jul 07 '11 10:07

Ondrej Slinták


1 Answers

Untested but you could try something like

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\Finder\Finder;

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

        if (in_array($this->getEnvironment(), array('dev', 'test'))) {
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            // ... 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');
    }
}
like image 167
Stefan Gehrig Avatar answered Nov 15 '22 16:11

Stefan Gehrig