When to use Entity Manager in Symfony2

Mats Rietdijk picture Mats Rietdijk · Aug 7, 2012 · Viewed 28.4k times · Source

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?

Answer

gremo picture gremo · Aug 7, 2012

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');
}