2012-08-07 73 views
15

目前我正在學習如何使用Symfony2。我到了他們解釋如何使用Doctrine的地步。何時使用Symfony2中的實體管理器

在給定的,他們有時會用實體管理器的實例:

$em = $this->getDoctrine()->getEntityManager(); 
$products = $em->getRepository('AcmeStoreBundle:Product') 
     ->findAllOrderedByName(); 

,並在其他例子中不使用實體管理器:

$product = $this->getDoctrine() 
     ->getRepository('AcmeStoreBundle:Product') 
     ->find($id); 

所以其實我嘗試的第一個例子沒有得到實體經理:

$repository = $this->getDoctrine() 
     ->getRepository('AcmeStoreBundle:Product'); 
$products = $repository->findAllOrderedByName(); 

並得到了同樣的結果。

那麼我什麼時候需要實體管理器,什麼時候可以一次去存儲庫呢?

回答

28

看着ControllergetDoctrine()等於$this->get('doctrine')Symfony\Bundle\DoctrineBundle\Registry的一個實例。註冊表提供:

因此,$this->getDoctrine()->getRepository()等於$this->getDoctrine()->getEntityManager()->getRepository()

$em = $this->getDoctrine()->getEntityManager(); 

$em->persist($myEntity); 
$em->flush(); 

如果你只是讀取數據,就可以得到只有庫:

$repository = $this->getDoctrine()->getRepository('AcmeStoreBundle:Product'); 
$product = $repository->find(1); 

或者更好,當你想持續存在或刪除實體

實體管理器是非常有用的,如果您使用自定義存儲庫,則可以將getRepository()包裝在控制器功能中,因爲您可以從IDE獲取自動完成功能:

/** 
* @return \Acme\HelloBundle\Repository\ProductRepository 
*/ 
protected function getProductRepository() 
{ 
    return $this->getDoctrine()->getRepository('AcmeHelloBundle:Product'); 
} 
+0

我已經知道在使用flush()時我需要使用實體管理器。另外使用'getProductRepository()'函數的想法可能是有用的,謝謝! – 2012-08-07 14:13:29

+1

@MatsRietdijk很高興爲您服務!我總是在自己的'BaseController'中將'$ this-> get('some service')'封裝在自定義函數中以獲得自動填充... – gremo 2012-08-07 14:35:34

+1

'AcmeStoreBundle:Product'的位置我可以在哪裏找到'Product'我的Symfony應用程序。 – 2016-07-11 11:56:57

2

我認爲getDoctrine()->getRepository()只是一個簡單的快捷方式getDoctrine()->getEntityManager()->getRepository()。沒有檢查源代碼,但聽起來對我來說很合理。

+0

謝謝,它似乎是一個捷徑。 – 2012-08-07 13:33:25

0

如果您計劃使用實體管理器執行多個操作(如獲取存儲庫,保存實體,刷新等),然後首先獲取實體管理器並將其存儲在變量中。否則,您可以從實體管理器獲取存儲庫,並在一行中調用任何您想要的存儲庫類中的方法。兩種方式都可以工作。這只是編碼風格和您的需求的問題。

相關問題