php - 是否可以在 Symfony2 中动态注册包?

标签 php symfony

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

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

我希望避免在 AppKernel::registerBundles() 中手动注册每个新包(在 Acme 目录中)。最好我希望 LoaderBundle 中的某些内容在每个请求上运行并动态注册 ToBeLoadedBundle1 和 ToBeLoadedBundle2 。可能吗?

最佳答案

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

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

关于php - 是否可以在 Symfony2 中动态注册包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6609240/

相关文章:

Symfony2 继承多个包

symfony - fosuserbundle 在 ovveriding loginaction 上收到错误消息

java - 如何从mysql php获取数据到android

php - 合并 xls 工作表中的单元格(xml 格式)

php - RabbitMq:替换重复的消息

php - PHP 中的 EPUB 阅读器/查看器

php - 如何获取 Symfony 控制台应用程序的运行路径?

php - Symfony 2 Controller 在转发到另一个 Controller 时丢失容器

php - 如何使用 paypal php sdk 设置项目的 "Options"?

php - Symfony 中的 Doctrine 迁移