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

前端 未结 4 710
你的背包
你的背包 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:44

    Yes, it's possible with two steps:

    1 - Override the doctrine.orm.entity_manager.class parameter to point to your custom entity manager (which should extend Doctrine\ORM\EntityManager.)

    2 - Your custom entity manager must override the create method so that it returns an instance of your class. See my example below, and note the last line regarding MyEntityManager:

    public static function create($conn, Configuration $config, EventManager $eventManager = null) {
            if (!$config->getMetadataDriverImpl()) {
                throw ORMException::missingMappingDriverImpl();
            }
    
            if (is_array($conn)) {
                $conn = \Doctrine\DBAL\DriverManager::getConnection($conn, $config, ($eventManager ? : new EventManager()));
            } else if ($conn instanceof Connection) {
                if ($eventManager !== null && $conn->getEventManager() !== $eventManager) {
                    throw ORMException::mismatchedEventManager();
                }
            } else {
                throw new \InvalidArgumentException("Invalid argument: " . $conn);
            }
    
            // This is where you return an instance of your custom class!
            return new MyEntityManager($conn, $config, $conn->getEventManager());
        }
    

    You'll also need to use the following in your class:

    use Doctrine\ORM\EntityManager;
    use Doctrine\ORM\Configuration;
    use Doctrine\ORM\ORMException;
    use Doctrine\Common\EventManager;
    use Doctrine\DBAL\Connection;
    

    To be honest, I'm surprised that the 2nd step is required at all, I would think this should be possible to accomplish using only the service container.

提交回复
热议问题