【问题标题】:True way to create extension for EntityManager为 EntityManager 创建扩展的真正方法
【发布时间】:2019-05-06 16:08:51
【问题描述】:

经常遇到如下一段代码:

catch (Exception $ex){
    $em->clear();
    if($em->getConnection()->isTransactionActive())
        $em->rollback();
    {somecode}
}

第一个想法-创建EntityManager的继承者,包含方法,实现清除和回滚,并将其放入DI容器中。但是注释中的 Doctrine EntityManager 类标记为 final:

/* final */class EntityManager implements EntityManagerInterface

作为服务的助手会很丑陋。有什么想法吗?

【问题讨论】:

    标签: php symfony entitymanager


    【解决方案1】:

    你会用装饰代替。大致如下所示:

    class MyEntityManager implements EntityManagerInterface
    {
        private $decoratedManager;
    
        public function __construct(EntityManagerInterface $entityManager)
        {
            $this->decoratedManager = $entityManager;
        }
    
        /**
         * Implement all methods on the interface like this:
         */
        public function persist($entity)
        {
            return $this->decoratedManager->persist($entity);
        } 
    }
    

    这不会破坏 final 并且您可以轻松地覆盖函数。然后在您的服务配置中,您必须覆盖实体管理器的服务定义,或者确保无论何时您想将EntityManagerInterface 注入到您的服务中。

    【讨论】:

      猜你喜欢
      • 2013-12-23
      • 1970-01-01
      • 2011-06-26
      • 2013-07-02
      • 1970-01-01
      • 2016-04-20
      • 1970-01-01
      • 2013-10-04
      • 1970-01-01
      相关资源
      最近更新 更多