Injecting dependency into entity repository
- by Hubert Perron
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 Doctrine\ORM\EntityManager::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 ?