我正在开发一个依赖于另一个的捆绑包。
为了处理未安装基本包的情况,我想在控制器内执行“bundle_exists()”函数。
问题是:如何获得已安装捆绑包的列表或如何检查捆绑包的名称(最终还包括版本)。
谢谢。
我正在开发一个依赖于另一个的捆绑包。
为了处理未安装基本包的情况,我想在控制器内执行“bundle_exists()”函数。
问题是:如何获得已安装捆绑包的列表或如何检查捆绑包的名称(最终还包括版本)。
谢谢。
除了@Rooneyl 的回答:
进行此类检查的最佳位置是在您的 DI 扩展中(例如AcmeDemoExtension
)。一旦构建容器并将其转储到缓存,就会执行此操作。无需在每个请求上检查此类内容(容器在缓存时不会更改),它只会减慢您的缓存速度。
// ...
class AcmeDemoExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container)
{
$bundles = $container->getParameter('bundles');
if (!isset($bundles['YourDependentBundle'])) {
throw new \InvalidArgumentException(
'The bundle ... needs to be registered in order to use AcmeDemoBundle.'
);
}
}
}
您的类需要能够访问容器对象(通过扩展或 DI)。
然后你可以做;
$this->container->getParameter('kernel.bundles');
这将为您提供已安装的捆绑包列表。
更新;
如果您在扩展 的控制器中Symfony\Bundle\FrameworkBundle\Controller\Controller
或在扩展的命令类中Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand
,则只需获取参数即可。
$this->getParameter('kernel.bundles')
.
否则@Wouter J 的答案是您的最佳答案。
您可以像这样从内核中获取所有捆绑包的列表:
public function indexAction ()
{
$arrBundles = $this->get("kernel")->getBundles();
if (!array_key_exists("MyBundle", $arrBundles))
{
// bundle not found
}
}
来自 Andrey 的这个问题:How do I get a list of bundles in symfony2?
如果要调用已注册的捆绑对象(不是类)的非静态方法,则可以执行以下操作:
$kernel = $this->container->get('kernel');
$bundles = $kernel->getBundles();
$bundles['YourBundleName']->someMethod();
你的包的名字在哪里'YourBundleName'
,你可以从控制台调用它:
php app/console config:dump-reference