我有一个加载程序包(LoaderBundle
),它应该在同一目录中注册其他包。
/Acme/LoaderBundle/...
/Acme/ToBeLoadedBundle1/...
/Acme/ToBeLoadedBundle2/...
我想避免在Acme
中手动注册每个新捆绑包(在AppKernel::registerBundles()
目录中)。我希望LoaderBundle
能够在每个请求上运行并动态注册ToBeLoadedBundle1
和ToBeLoadedBundle2
。有可能吗?
答案 0 :(得分:9)
未经测试但您可以尝试类似
的内容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');
}
}
答案 1 :(得分:-2)
之前的回答包含一个小错误,其中包含带有/在前面的类,这里是更新的代码
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();
}