我有一个关于Symfony2控制器扩展的问题。目前,我一直在为我的应用程序中的每个控制器扩展一个FrameworkBundle。但我通过制作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();
}
}
我无法加载$这个 - > EM和$这个 - >用户自容器__construct()函数不是在施工时加载。
所以我的问题是:
- 那是一个好主意,或者我应该继续做详细的电话?
- 只是创建可以完成同样工作的函数getEm()和getUser()会更好吗?
谢谢!
好主意,我会做同样的:) – Nanocom
这里是摘录: 'public function getEm(){ return $ this-> getDoctrine() - > getEntityManager(); } public function getRepository($ shortEntityName){ return $ this-> getEm() - > getRepository(“SicoStockBundle:$ shortEntityName”); }' –