I want to make a repository with hard dependencies. I found this blog post by Jurian Sluisman but he suggests getting the repository from the service manager and injecting it into the service where needed.
It would be much better if I would be able to get my custom repositories with injected dependencies like normally from my EntityManager
or ObjectManager
instance by using the getRepository
method:
$objectManager->getRepository('My\Entity\Class');
How can I use constructor injection in my Repositories and still get them like normally from the ObjectManager
directly with the getRepository
method?
Doctrine uses a factory class
Doctrine\ORM\EntityManagerInterface\DefaultRepositoryFactory
for creating repository instances. If no custom factory is set this default factory is created here in thegetRepositoryFactory
method in theDoctrine\ORM\Configuration
class.By defining a custom
repository_factory
we can overwrite this default factory class and add custom logic to the factory that will inject the hard dependencies:To illustrate how you can do this I will show an example where the repository factory class creates repositories that are dependent on a
ServiceLocator
instance through constructor injection.1) make a custom factory class that implements the doctrine
RepositoryFactory
interfaceThis class looks very similar to the doctrine
DefaultRepositoryFactory
class.2) Create a factory for the repository factory
3) register the factory for the repository factory in the
service_manager
config4) register the repository factory in the doctrine config