Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 为EntityManager创建扩展的真正方法_Php_Symfony_Entitymanager - Fatal编程技术网

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