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?
I think that the
getDoctrine()->getRepository()
is simply a shortcut togetDoctrine()->getEntityManager()->getRepository()
. Did not check the source code, but sounds rather reasonable to me.Looking at
Controller
getDoctrine()
equals to$this->get('doctrine')
, an instance ofSymfony\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:
If you are just fetching data, you can get only the repository:
Or better, if you are using custom repositories, wrap
getRepository()
in a controller function as you can get auto-completition feature from your IDE: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.