1

I want to register all Doctrine repositories as services

I found this approach: How to configure dependency injection for repository class in symfony 3

But this way I have to register every single one repository manually.

I'd like to create some Service Factory that would instantiate repositories for me given just a repository class name.

Something like this:

namespace AppBundle\Service;

use Doctrine\ORM\EntityManagerInterface;

class RepositoryFactory
{
    /**
     * @var EntityManagerInterface
     */
    private $manager;

    public function __construct(EntityManagerInterface $manager)
    {
        $this->manager = $manager;
    }

    public function getRepository(string $repositoryClass)
    {
        // do some magic that somehow obtaining actual repo
        return $repo;
    }
}

service.yml

AppBundle\Service\RepositoryFactory:
  autowire: true

but Symfony's docs say nothing about how to pass service name that you want to instantiate (if it's even possible) in this factory

You Care
  • 488
  • 4
  • 20
  • Possible duplicate of [How to inject a repository into a service in Symfony2?](https://stackoverflow.com/questions/12223176/how-to-inject-a-repository-into-a-service-in-symfony2) – Alister Bulman Sep 16 '17 at 19:58
  • You are basically asking autowire to inject a repository based strictly on the repo class name. Don't think it will happen especially if you take into account multiple entity managers. – Cerad Sep 17 '17 at 03:09
  • What you saying is possible duplicate I just posted it as an example right in my question, and explained why it isn't convenient. – You Care Sep 18 '17 at 08:48
  • I don't want it automagically happen, It is possible to figure out the repo by its name simply by iterating the entity's metadata and check which @Repository annotation has this particular class, but I should do it in the factory, but DI says nothing about which service I'm about to instantiate. Like I have to have a factory for just one class, which is boring. My answer is how (if possible) can I provide class (service name) to the factory – You Care Sep 18 '17 at 08:51
  • It is not duplicate of [How to inject a repository into a service in Symfony2](https://stackoverflow.com/questions/12223176/how-to-inject-a-repository-into-a-service-in-symfony) The repository context of topic is same, but question title states it clearly that it is common question about how to create factory which accepts class name of objecet to be created – Arkemlar Mar 20 '19 at 11:15

0 Answers0