如何在Symfony 2中获取当前的bundle?

10

我该如何检测自己在哪个捆绑包中?

例如,当我在web.com/participants/list时,我想读取“participants”。

4个回答

15

为了在控制器中获取束(bundle)名称

// Display "AcmeHelloBundle"
echo $this->getRequest()->attributes->get('_template')->get('bundle');

并且在Twig模板中:

{{ app.request.get('_template').get('bundle') }}

为了在控制器中获取控制器名称

// Display "Default"
echo $this->getRequest()->attributes->get('_template')->get('controller');

在Twig模板中:

{{ app.request.get('_template').get('controller') }}

为了在控制器中获取操作名称

// Displays "index"
echo $this->getRequest()->attributes->get('_template')->get('name');

在Twig模板中:

{{ app.request.get('_template').get('name') }}

6
如果你没有使用@template注释,我相当确定->attributes->get('_template')是不可用的。 - Leevi Graham
在控制器中,您可以使用$request->attributes->get('_controller');$this->getRequest()->attributes->get('_controller');来获取控制器名称。 - Shadman

7
据我所知,目前还没有一个简单的方法来完成这个(至少我不知道)。您应该使用反射(reflection)。我编写了一个快速且简陋的服务来根据我的约定获取包名称和猜测实体/仓库/表单名称。但可能会有错误,请看这里:http://pastebin.com/BzeXAduH 它只适用于传递自Controller(Symfony2)继承的类。使用方法:
entity_management_guesser:
  class: Acme\HelloBundle\Service\EntityManagementGuesser

在你的控制器中:
$guesser = $this->get('entity_management_guesser')->inizialize($this);

$bundleName  = $guesser->getBundleName();      // Acme/HelloBundle
$bundleShort = $guesser->getBundleShortName(); // AcmeHelloBundle

另一种可能是使用内核获取所有的捆绑包:从实体中获取捆绑包名称

自回复以来已经过去了2.5年,有人听说这个问题有任何进展吗? :) 有没有更“简洁”的方法来查找捆绑包名称? :) - Dimitry K

6

你可以通过以下方式获取当前路由的控制器:

$request->attributes->get('_controller');

您可以从中解析出捆绑包名称。

3

您可以在控制器中简单地获取bundle名称,如下所示:

// Display "SybioCoreBundle"
echo $this->getRequest()->attributes->get('_template')->get('bundle');

在Twig模板中:

{{ app.request.get('_template').get('bundle') }}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接