Injecting dependency into entity repository

后端 未结 6 1487
有刺的猬
有刺的猬 2020-12-13 04:46

Is there a simple way to inject a dependency into every repository instance in Doctrine2 ?

I have tried listening to the loadClassMetadata event and usi

6条回答
  •  無奈伤痛
    2020-12-13 04:59

    If you use a custom EntityManager you could override the getRepository method. Since this doesn't involve the loadClassMetadata event, you won't run into an infinite loop.

    You would first have to pass the dependency to your custom EntityManager, and then you'd pass it to the repository object using setter injection.

    I answered how to use a custom EntityManager here, but I'll replicate the answer below:

    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;
    

    Edit

    Since the default entity manager is created from the create method, you can't simply inject a service into it. But since you're making a custom entity manager, you can wire it up to the service container and inject whatever dependencies you need.

    Then from within the overridden getRepository method you could do something like
    $repository->setFoo($this->foo). That's a very simple example - you may want to first check if $repository has a setFoo method before calling it. The implementation is up to you, but this shows how to use setter injection for a repository.

提交回复
热议问题