How to use entityManager inside Entity?

烂漫一生 提交于 2019-12-04 03:44:08

问题


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 ?


回答1:


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 :(




回答2:


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');


来源:https://stackoverflow.com/questions/11079509/how-to-use-entitymanager-inside-entity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!