When to use Entity Manager in Symfony2

2019-03-12 13:46发布

At the moment I am learning how to use Symfony2. I got to the point where they explain how to use Doctrine.

In the examples given they sometimes use the entity manager:

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

and in other examples the entity manager is not used:

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

So I actually tried the first example without getting the entity manager:

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

and got the same results.

So when do i actually need the entity manager and when is it OK to just go for the repository at once?

3条回答
一纸荒年 Trace。
2楼-- · 2019-03-12 13:50

I think that the getDoctrine()->getRepository() is simply a shortcut to getDoctrine()->getEntityManager()->getRepository(). Did not check the source code, but sounds rather reasonable to me.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-03-12 14:01

Looking at Controller getDoctrine() equals to $this->get('doctrine'), an instance of Symfony\Bundle\DoctrineBundle\Registry. Registry provides:

Thus, $this->getDoctrine()->getRepository() equals $this->getDoctrine()->getEntityManager()->getRepository().

Entity manager is useful when you want to persist or remove an entity:

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

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

If you are just fetching data, you can get only the repository:

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

Or better, if you are using custom repositories, wrap getRepository() in a controller function as you can get auto-completition feature from your IDE:

/**
 * @return \Acme\HelloBundle\Repository\ProductRepository
 */
protected function getProductRepository()
{
    return $this->getDoctrine()->getRepository('AcmeHelloBundle:Product');
}
查看更多
干净又极端
4楼-- · 2019-03-12 14:14

If you plan to do multiple operations with the entity manager (like get a repository, persist an entity, flush, etc), then get the entity manager first and store it in a variable. Otherwise, you can get the repository from the entity manager and call whatever method you want on the repository class all in one line. Both ways will work. It's just a matter of coding style and your needs.

查看更多
登录 后发表回答