2011-10-10 97 views
1

我有一個關於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()會更好嗎?

謝謝!

回答

0

我創建了MyController,但也創建了MyRepository。然後所有的控制器和存儲庫擴展這些類。我也調用$ this-> getRepository(「User」),而不是$ this-> getDocrine() - > getEntityManager() - > getrepository(「MyappBundle:User」);

+0

好主意,我會做同樣的:) – Nanocom

+0

這裏是摘錄: 'public function getEm(){ return $ this-> getDoctrine() - > getEntityManager(); } public function getRepository($ shortEntityName){ return $ this-> getEm() - > getRepository(「SicoStockBundle:$ shortEntityName」); }' –

4

我有同樣的問題,我剛創建了一個自定義控制器,有getUser()getEntityManager()方法。它完美的作品。我建議在這種情況下使用getter方法而不是類實例,只是爲了與Symfony2期望您請求服務的方式保持一致。

供參考,這是我的getUser方法:

public function getUser() { 
     $user = $this->get('security.context')->getToken()->getUser(); 
     return $user; 
} 
+0

好吧,這就是我的想法。這是不是創建「RootBundle」的好主意? – Nanocom

+0

您可以,但我將自定義控制器保留在供應商目錄中。我沒有看到需要把它放在自己的包中。無論哪種方式應該工作得很好,所以歸結爲個人偏好。 –

0

另一種選擇是你定義控制器爲服務,並指定什麼獲取傳遞給你的構造函數,以任何你想要的私有變量,但下跌空間可能你不會喜歡這條路線需要的所有設置

0

你可以注入的EntityManager(或任何其他服務),即使沒有控制器extantion爲:

use JMS\DiExtraBundle\Annotation as DI; 

    class IndexController extends Controller 
    { 
     /** 
     * @DI\Inject("doctrine.orm.entity_manager") 
     * @var \Doctrine\ORM\EntityManager $em 
     */ 
     protected $em;