Подтвердить что ты не робот

Можно ли динамически регистрировать пакеты в Symfony2?

У меня есть пакет загрузчика (LoaderBundle), который должен регистрировать другие пакеты в одном каталоге.

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

Я бы не стал вручную регистрировать каждый новый пакет (в каталоге Acme) в AppKernel::registerBundles(). Желательно, чтобы что-то в LoaderBundle выполнялось по каждому отдельному запросу и динамически регистрировало ToBeLoadedBundle1 и ToBeLoadedBundle2. Возможно ли это?

4b9b3361

Ответ 1

Неподтвержденный, но вы можете попробовать что-то вроде

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

Ответ 2

В предыдущем ответе была небольшая ошибка, в которой он включал бы класс с a/спереди, вот обновленный код

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