Php 为EntityManager创建扩展的真正方法
经常遇到以下代码:Php 为EntityManager创建扩展的真正方法,php,symfony,entitymanager,Php,Symfony,Entitymanager,经常遇到以下代码: catch (Exception $ex){ $em->clear(); if($em->getConnection()->isTransactionActive()) $em->rollback(); {somecode} } 第一个想法-创建EntityManager的继承者,包含方法,实现clear和rollback,并将其放在DI容器中。但注释标记中的条令EntityManager类为最终: /* fi
catch (Exception $ex){
$em->clear();
if($em->getConnection()->isTransactionActive())
$em->rollback();
{somecode}
}
第一个想法-创建EntityManager的继承者,包含方法,实现clear和rollback,并将其放在DI容器中。但注释标记中的条令EntityManager类为最终:
/* final */class EntityManager implements EntityManagerInterface
作为服务的助手将是丑陋的。有什么想法吗?你可以用装饰来代替。大致如下所示:
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注入到服务中时,都会选择您的EntityManagerInterface