How to inject a repository into a service in Symfony?

前端 未结 5 1623
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-30 21:39

I need to inject two objects into ImageService. One of them is an instance of Repository/ImageRepository, which I get like this:

$         


        
5条回答
  •  一生所求
    2020-11-30 22:27

    Symfony 3.3, 4 and 5 makes this much simpler.

    Check my post How to use Repository with Doctrine as Service in Symfony for more general description.

    To your code, all you need to do is use composition over inheritance - one of SOLID patterns.

    1. Create own repository without direct dependency on Doctrine

    repository = $entityManager->getRepository(Image::class);
        }
    
        // add desired methods here
        public function findAll()
        {
            return $this->repository->findAll();
        }
    }
    

    2. Add config registration with PSR-4 based autoregistration

    # app/config/services.yml
    services:
        _defaults:
            autowire: true
    
        MycompanyMainBundle\:
            resource: ../../src/MycompanyMainBundle
    

    3. Now you can add any dependency anywhere via constructor injection

    use MycompanyMainBundle\Repository\ImageRepository;
    
    class ImageService
    {
        public function __construct(ImageRepository $imageRepository)
        {
            $this->imageRepository = $imageRepository;
        }
    }
    

提交回复
热议问题