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?
Looking at
ControllergetDoctrine()equals to$this->get('doctrine'), an instance ofSymfony\Bundle\DoctrineBundle\Registry. Registry provides:getEntityManager()returningDoctrine\ORM\EntityManager, which in turn providesgetRepository()getRepository()returningDoctrine\ORM\EntityRepositoryThus,
$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: