Is there a way to specify Doctrine2 Entitymanager implementation class in Symfony2?

前端 未结 4 712
你的背包
你的背包 2020-11-30 08:18

I\'m currently working with Symfony2 and Doctrine2, but I must override the Doctrine2 EntityManager and add it some \"undelete\" features (ACLs inside).

So I\'m wond

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 08:46

    At least in Doctrine/ORM 2.4, the doc string of the EntityManager class explicitly discourages inheriting from Doctrine\ORM\EntityManager, instead they suggest inheriting from Doctrine\ORM\Decorator\EntityManagerDecorator:

    /**
     * The EntityManager is the central access point to ORM functionality.
     * ...
     * You should never attempt to inherit from the EntityManager: Inheritance
     * is not a valid extension point for the EntityManager. Instead you
     * should take a look at the {@see \Doctrine\ORM\Decorator\EntityManagerDecorator}
     * and wrap your entity manager in a decorator.
     * ...
     */
    /* final */class EntityManager implements EntityManagerInterface
    {
        ...
    

    So, extend EntityManagerDecorator and make whatever changes you need. You will need to implement the create() factory method, but you don't need to copy EntityManager's implementation now:

    use Doctrine\ORM\Decorator\EntityManagerDecorator;
    use Doctrine\Common\EventManager;
    use Doctrine\ORM\Configuration;
    
    class MyEntityManager extends EntityManagerDecorator
    {
        /**
         * {@inheritDoc}
         */
        public function persist($entity)
        {
            // do something interesting
            parent::persist($entity);
        }
    
        public function create($conn, Configuration $config, EventManager $eventManager = null)
        {
            return new self(\Doctrine\ORM\EntityManager::create($conn, $config, $eventManager));
        }
    }
    

    Then override the doctrine.orm.entity_manager.class parameter to point to your custom entity manager class.

    The docs don't cover everything, in many cases you just have to read the code.

提交回复
热议问题