6

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.

Nick
  • 2,872
  • 3
  • 34
  • 43

2 Answers2

8

You do not have to define your controller as a service in order to access the EntityManager. The Controller::getDoctrine() method mentioned above simply returns the Doctrine Registry by calling $this->container->get('doctrine') after checking that the doctrine service is actually available.

Simply make your custom class/controller extend ContainerAware and define a shortcut method like:

public function getEntityManager() {
    return $this->container->get('doctrine')->getEntityManager();
}

Note that it's $this->container->get(..) and not $this->get(..) in a class extending/implementing ContainerAware.

dylan oliver
  • 1,274
  • 9
  • 16
6

You need to inject the entity manager service into your custom service. Your service definition should look like this:

my.service.name:
  class:     my\class
  arguments: [ @doctrine.orm.default_entity_manager ]

Make sure that your service's __construct method 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 extends Symfony\Bundle\FrameworkBundle\Controller\Controller

Steven Mercatante
  • 24,757
  • 9
  • 65
  • 109
  • In Symfony 2.3 I'm using "@doctrine.orm.entity_manager". Is there a difference between "@doctrine.orm.entity_manager" and "@doctrine.orm.default_entity_manager" ? – Jay Sheth Mar 21 '14 at 20:19