0

I'm doing a query on an entity, but of course I am asked to instantiate doctrine entityManager my serious question:

As instantiate the EntityManager to use in the entity.

Excuse my English, I am using google truth XD, as not meeting ZF2 communities and Doctrine2 in Spanish.

1 Answers1

1

If I understood your question you want to get the entityManager inside your Doctrine entities, right ?

I don't think it's good idea to usee the EntityManager within your Doctrine entities. But for this, you need first to get an instance of the service manager in your entity class.

By default, the Zend Framework MVC registers an initializer that will inject the ServiceManager instance, which is an implementation of Zend\ServiceManager\ServiceLocatorInterface, into any class implementing Zend\ServiceManager\ServiceLocatorAwareInterface

For Doctrine, we have to make the service manager available within the entities. So You have to implement the ServiceLocatorAwareInterface for each entity or simpler create a class which implements Zend\ServiceManager\ServiceLocatorAwareInterface and then simply make the entities that need access to the service manager inherit from this class.

Here is a good post on HOW TO INJECT ZF2 SERVICE MANAGER INTO DOCTRINE ENTITIES

Following this post, you could simply get the entityManager within your entity like this :

$em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
blackbishop
  • 30,945
  • 11
  • 55
  • 76
  • Thanks, it was exactly what I needed and it works. Now you tell me that is not good practice, so now I have another question. Where should I go query I am doing, if I can not call EntityManager from the entity. This consultation should go in the driver or where? – Andres Echeverry Apr 02 '15 at 18:26