Is there a simple way to inject a dependency into every repository instance in Doctrine2 ?
I have tried listening to the loadClassMetadata
event and using setter injection on the repository but this naturally resulted in a infinite loop as calling getRepository
in the event triggered the same event.
After taking a look at the DoctrineORMEntityManager::getRepository
method it seems like repositories are not using dependency injection at all, instead they are instantiated at the function level:
public function getRepository($entityName)
{
$entityName = ltrim($entityName, '\');
if (isset($this->repositories[$entityName])) {
return $this->repositories[$entityName];
}
$metadata = $this->getClassMetadata($entityName);
$customRepositoryClassName = $metadata->customRepositoryClassName;
if ($customRepositoryClassName !== null) {
$repository = new $customRepositoryClassName($this, $metadata);
} else {
$repository = new EntityRepository($this, $metadata);
}
$this->repositories[$entityName] = $repository;
return $repository;
}
Any ideas ?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…