【问题标题】:How to use entityManager inside Entity?如何在 Entity 中使用 entityManager?
【发布时间】:2012-06-18 08:48:10
【问题描述】:

我在 Entity 类中有这个功能,但 getDoctrine 不喜欢...

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;
    }
}

如何在我的实体中使用 entityManager ?

【问题讨论】:

标签: symfony doctrine-orm entity entitymanager


【解决方案1】:

实际上 Entity 不应该知道 EM。如果我需要在我的实体中使用高级逻辑,我会使用事件监听器。当您像服务一样注册侦听器时,您可以在那里传递参数,例如 EM 或容器,然后将它们放入侦听器类中。

Symfony Doc

但我知道在实体类中获取 EM 并不是很好的方法。通过在 Entity 方法中获取全局变量 Kernel。

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

为我感到羞耻:(

【讨论】:

  • 您如何看待实体实现\Doctrine\Common\Persistence\ObjectManagerAware?补水时UnitOfWork 就可以了。
【解决方案2】:

在 services.yml 添加这个

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

在经理中-

private $_container;


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

访问管理器-

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

【讨论】:

  • 注入容器是一种不好的做法。注入整个服务容器只是为了获得实体管理器,这简直是天方夜谭。尽管在某些情况下这可能是一个快速而肮脏的解决方案,例如避免循环引用。
猜你喜欢
  • 2013-01-19
  • 2012-03-31
  • 2017-02-12
  • 1970-01-01
  • 2013-05-15
  • 1970-01-01
  • 2011-12-26
  • 2011-07-13
  • 2012-06-28
相关资源
最近更新 更多