October 17, 2012

Symfony2: Repositories in DIC

Easy recipe to define a Doctrine repository in your Dependency Injection Container:
Edit services.yml and add this one:
services:
    myentity.repository:
        class: Doctrine\ORM\EntityRepository
        factory_service: doctrine.orm.entity_manager
        factory_method: getRepository
        arguments: [MyBundle:MyEntity]

I'm used to YAML, but if you're into XML, the solution should be similar. Please share it for completeness sake ;)

Then you can do this inside actions in the controller:
$repository = $this->get('myentity.repository');
// Work with the repository, p.e:
$all_myentities = $repository->findAll();
// ...

And that's all! Easy as pie! See you soon :)