【发布时间】:2015-04-07 04:48:31
【问题描述】:
我有一个关于 Symfony2 控制器扩展的问题。目前,我一直在为我的应用程序中的每个控制器扩展一个 FrameworkBundle。但是我已经厌倦了总是通过制作一个
来检索用户$this->get('security.context')->getToken()->getUser()
或者一个
$this->getDoctrine()->getEntityManager()
每次我需要用户或实体管理员时(我非常需要他们)。我希望能够通过执行 $this->em 和 $this->user 来检索它们。 所以我决定创建一个名为 MyApp/RootBundle 的包,其中包含一个扩展 FrameworkBundle 的新控制器。该控制器将被应用程序中的所有其他控制器扩展。这是代码:
<?php
namespace MyApp\RootBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\DependencyInjection\ContainerInterface;
class RootController extends Controller
{
protected $em;
protected $user;
public function setContainer(ContainerInterface $container = null)
{
parent::setContainer($container);
$this->onContainerSet();
}
public function onContainerSet()
{
$this->em = $this->getDoctrine()->getEntityManager();
$this->user = $this->get('security.context')->getToken()->getUser();
}
}
我无法在 __construct() 函数中加载 $this->em 和 $this->user,因为在构建时未加载容器。
所以我的问题是:
- 这是个好主意还是我应该继续进行冗长的调用?
- 创建功能相同的 getEm() 和 getUser() 会更好吗?
谢谢!
【问题讨论】:
标签: controller symfony