How to inject a repository into a service in Symfony? How to inject a repository into a service in Symfony? symfony symfony

How to inject a repository into a service in Symfony?


Here is a cleaned up solution for those coming from Google like me:

Update: here is the Symfony 2.6 (and up) solution:

services:    myrepository:        class: Doctrine\ORM\EntityRepository        factory: ["@doctrine.orm.entity_manager", getRepository]        arguments:            - MyBundle\Entity\MyClass    myservice:        class: MyBundle\Service\MyService        arguments:            - "@myrepository"

Deprecated solution (Symfony 2.5 and less):

services:    myrepository:        class: Doctrine\ORM\EntityRepository        factory_service: doctrine.orm.entity_manager        factory_method: getRepository        arguments:            - MyBundle\Entity\MyClass    myservice:        class: MyBundle\Service\MyService        arguments:            - "@myrepository"


I found this link and this worked for me:

parameters:    image_repository.class:            Mycompany\MainBundle\Repository\ImageRepository    image_repository.factory_argument: 'MycompanyMainBundle:Image'    image_manager.class:               Mycompany\MainBundle\Service\Image\ImageManager    image_manipulator.class:           Mycompany\MainBundle\Service\Image\ImageManipulatorservices:    image_manager:        class: %image_manager.class%        arguments:          - @image_manipulator          - @image_repository    image_repository:        class:           %image_repository.class%        factory_service: doctrine.odm.mongodb        factory_method:  getRepository        arguments:            - %image_repository.factory_argument%    image_manipulator:        class: %image_manipulator.class%


In case if do not want to define each repository as a service, starting from version 2.4 you can do following, (default is a name of the entity manager):

@=service('doctrine.orm.default_entity_manager').getRepository('MycompanyMainBundle:Image')