When to use Entity Manager in Symfony2
Looking at Controller
getDoctrine()
equals to $this->get('doctrine')
, an instance of Symfony\Bundle\DoctrineBundle\Registry
. Registry provides:
getEntityManager()
returningDoctrine\ORM\EntityManager
, which in turn providesgetRepository()
getRepository()
returningDoctrine\ORM\EntityRepository
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');}
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.
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.