How to use entityManager inside Entity?

眉间皱痕 提交于 2019-12-01 18:43:07

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

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