I want to enable easy autowiring for my Repositories. At the same time I need to be able to switch DB connections on them (so define them in services.yaml with different db conn)
I extend all my Repos from a BaseRepository which implements ServiceEntityRepositoryInterface and extends EntityRepository
The constructor looks like this:
public function __construct(ManagerRegistry $registry, $entityClass, $connection = "default")
{
$manager = $registry->getManager($connection);
parent::__construct($manager, $manager->getClassMetadata($entityClass));
}
Now the constructor of most of my Repositories themselves look like this:
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, MyEntity::class);
}
Some have an extra $connection argument to allow overwriting their connection. Since sometimes I need repos accessing different databases.
This works perfectly in my frontend and gets just autowired without even defining anything besides a generic loading of all services/repositories in the services.yaml
In Tests I want to get these repos aswell.
I do this, in a base test class
$this->em = $this->bootedKernel->getContainer()->get('doctrine')->getManager();
In my test then I want to do
$this->myRepo = $this->em->getRepository(MyEntity::class);
This horribly fails with
RuntimeException: The "\Moebel\MyApp\Repository\MyEntityRepository" entity repository implements "Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepositoryInterface", but its service could not be found. Make sure the service exists and is tagged with "doctrine.repository_service
I have tried tagging the repositories in the services.yaml but it made no difference. I looked through some of the symfonfy code and saw this:
(in ContainerRepositoryFactory)
return $this->managedRepositories[$repositoryHash] = new $repositoryClassName($entityManager, $metadata);
I don't read symfony code a lot but this looks like to me the code that getRepository uses calls my class with an entityManager which is wrong for me. I want the ManagerRegistry.
What's the best way to fix my issues with Doctrine and Repositories?
Edit: I found a solution, but not for all Problems. Directly using the container and not letting doctrine fetch the repo so like this:
self::$container->get(MyEntityRepository::class);
Maybe anyone has a better idea? Because now I can't get Repos with different connections, or I'm unsure how.