In Symfony2, how can I go about adding Doctrine’s entity manager to a custom class or service?
I have tried $em = $this->get("doctrine.orm.entity_manager");
and $em = $this->getDoctrine()->getEntityManager();
Both failed, which led me to try and extend the Controller class with my custom class/service, and that died in a giant ball of fire.
You need to inject the entity manager service into your custom service. Your service definition should look like this:
Make sure that your service’s
__constructmethod takes the entity manager as an argument.See the Service Container chapter for more info.
BTW,
$this->getDoctrine()is a shortcut method that will only work in a class that extendsSymfony\Bundle\FrameworkBundle\Controller\Controller