How to get entity manager for Doctrine entity with Symfony 2.1 from inside controller

Slava Fomin II picture Slava Fomin II · Oct 6, 2012 · Viewed 51.5k times · Source

How can I get an entity manager from inside a controller with latest Symfony and Doctrine?

The way described in "The Book" flagged as deprecated now. What is a modern (proper) way to do this?

public function someAction()
{
    // getEntityManager() from Doctrine\Bundle\DoctrineBundle\Registry is deprecated
    $entityManager = $this->getDoctrine()->getEntityManager();
    ...
}

Answer

Elnur Abdurrakhimov picture Elnur Abdurrakhimov · Oct 7, 2012

Use $this->getDoctrine()->getManager() instead.

Actually, it's best not to make controllers aware of the persistence layer you're using. That stuff should be moved to the Service Layer to abstract the way the data is persisted.