How to use entityManager inside Entity?

I have this function in the Entity class, but getDoctrine does not like ...

public function getObject() { $em = $this->getDoctrine()->getEntityManager(); switch($this->objectType) { case 'video': return $em->getRepository('fdj2012AdminBundle:Video')->find($this->objectId); break; case 'default': return false; break; } } 

How to use entityManager inside my object?

+4
source share
2 answers

Actually, the entity should not know about EM. I use event listeners if I need some preliminary logic in my Entity. When you register Listeners like services, you can pass args there, such as EM or Container, and get them inside the Listener class.

Symfony doc

But I don't know if there is really a good way to get EM inside an Entity class. Accepting Kernel global variables in Entity methods.

 global $kernel; if ( 'AppCache' == get_class($kernel) ) { $kernel = $kernel->getKernel(); } $em = $kernel->getContainer()->get( 'doctrine.orm.entity_manager' ); 

Shame on me: (

+10
source

In services.yml add this

 access_manager: class: AppBundle\Services\EntityManager arguments: [ @service_container ] 

In Manager -

 private $_container; public function __construct(ContainerInterface $container) { $this->_container = $container; } 

To access the dispatcher -

  $entity2Manager = $this->_container->get('entity2_manager'); 
-1
source

All Articles