Declaring Doctrine repositories as services

Published on 2019-08-27 • Modified on 2019-08-27

This my preferred way to declare and use Doctrine repositories. It allows to directly inject it wherever you need. Moreover, you have auto-completion in the IDE (PhpStorm with the Symfony plugin for example) as the service class is known. It's not the case when directly using the Doctrine getRepository() function inside a controller.

# config/packages/doctrine.yaml
        class: App\Entity\ArticleRepository
        factory: ['@doctrine.orm.default_entity_manager', getRepository]
            - App\Entity\Article

Bonus, the snippet to run this code: 🎉
<?php declare(strict_types=1);

// src/Controller/Snippet/Snippet40Trait.php

namespace App\Controller\Snippet;

use App\Entity\ArticleRepository;
use Symfony\Component\HttpFoundation\Request;

 * I am using a PHP trait in order to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Sf 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Sf <= 4.1)
 * Services are injected in the controller constructor.
trait Snippet40Trait
    public function snippet40(Request $request, ArticleRepository $articleRepo): void
        // In fact the article repository is injected in the parent controller constructor
        // then passed as the second argument of the snippet40 function.
        $articles = $articleRepo->findArticlesForLang('en');

        //  We've got autocompletion on the ArticleRepository functions like "findArticlesForLang".

        echo sprintf('%d posts found! 📚', count($articles));

        // That's it! 😁

 Run this snippet  More on Stackoverflow  More on the web