How to configure dependency injection for repository class in symfony 3

Recommended as of Symfony 3.3:

As of Symfony 3.3 it is recommended to use the actual class name as service id (read this and this).

AppBundle\Repository\GroupEntityRepository:
    factory: 'Doctrine\ORM\EntityManagerInterface:getRepository'
    arguments:
        - AppBundle\Entity\GroupEntity

Original answer:

You can configure your repository service like this:

group_entity_repository:
    class: AppBundle\Repository\GroupEntityRepository
    factory: ["@doctrine.orm.entity_manager", getRepository]
    arguments:
        - AppBundle\Entity\GroupEntity

You will probably never want to invoke the repository constructor yourself. Therefore this approach just uses the entity_manager to get the repository. The service container bascially uses this code to get the repository:

$container->get('doctrine.orm.entity_manager')->getRepository('AppBundle\Entity\GroupEntity');

Since Symfony 3.4 you can avoid factory and use a TagRepository service that extends ServiceEntityRepository class instead of directly EntityRepository.

use AppBundle\Entity\GroupEntity;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Symfony\Bridge\Doctrine\RegistryInterface;

class GroupEntityRepository extends ServiceEntityRepository
{
    public function __construct(RegistryInterface $registry)
    {
        parent::__construct($registry, GroupEntity::class);
    }
}

With this method, your service would be automatically registered with autowiring feature.

You can also do better in all Symfony version by using composition over inheritance.

final class GroupEntityRepository
{
    /** @var EntityManagerInterface */
    private $entityManager;

    /** @var ObjectRepository */
    private $objectRepository;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
        $this->objectRepository = $this->entityManager->getRepository(GroupEntity::class);
    }

This service can also be autowiring. You can go further by respecting the SOLID principle and create an interface. There is a good explanation in this article (Repository Pattern in Symfony)

Tags:

Symfony