6

I have this function in Entity class but the getDoctrine do not fond...

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 Entity ?

j0k
  • 22,600
  • 28
  • 79
  • 90
Antoine Lenoir
  • 524
  • 1
  • 3
  • 17
  • 3
    Possible duplicate of [Using EntityManager inside Doctrine 2.0 entities](http://stackoverflow.com/questions/4108291/using-entitymanager-inside-doctrine-2-0-entities). Your entities shouldn't know about the entity manager, but rather you should pass any data/services required into your entities as and when required. – richsage Jun 18 '12 at 09:01
  • I get this from twig template... But I'm going to deepen that. Thanks – Antoine Lenoir Jun 18 '12 at 09:09
  • Do yo need table inheritance ? -> http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/inheritance-mapping.html – Antoine REYT Mar 13 '13 at 22:33

2 Answers2

10

Actually Entity shouldn't know about EM. I use Event Listeners if I need advance logic in my Entity. When you register Listeners like services you can pass args there, like a EM or Container and get them inside Listener class.

Symfony Doc

But I know not really good way to get EM inside Entity class. By taking global variable Kernel in Entity methods.

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

Shame on me :(

sean662
  • 696
  • 6
  • 15
  • What do you think about Entity implementing `\Doctrine\Common\Persistence\ObjectManagerAware`? when hydrating `UnitOfWork` does the job. – juanmf Jul 15 '14 at 19:18
-1

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 manager-

        $entity2Manager = $this->_container->get('entity2_manager');
Dhawal Naik
  • 450
  • 3
  • 6
  • It is a bad practice to inject the container. Injecting the whole service container just to get the entity manager is breaking a fly on the wheel. Although this can be a quick and dirty solution in some cases, like avoiding circular references. – cezar Apr 12 '16 at 13:04