【问题标题】: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 注入到您的服务中。