Learn how to retrieve the entity manager to interact with your database inside a command in Symfony 5.

One of the most usual things that we do with commands in Symfony, is the simple fact of modifying stuff on the database according to specific conditions in our application. Accessing the database through the entity manager in controller and services is quite simple and easy to do. In Commands, it's quite easy as well, but it isn't documented and explained in the official documentation. Just like everything in Symfony 5, you may inject services through the constructor of Services and Commands, so to obtain the EntityManager inside a command, you would only need to inject theĀ EntityManagerInterface like this:

<?php

namespace App\Command;

// ...

use Doctrine\ORM\EntityManagerInterface;

class ExampleCommand extends Command
{
    // ...

    private $entityManager;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;

        parent::__construct();
    }
    
    // ...
}

The entity manager will be accessible to the entire class and you will be able to run queries, create and persist entities like you usually do in controllers and services.

Example

The following ExampleCommand.php file contains the above explained logic. You may simply update the code of the command and change the name:

<?php

// src/Command/ExampleCommand.php
namespace App\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

// 1. Import the ORM EntityManager Interface
use Doctrine\ORM\EntityManagerInterface;

class ExampleCommand extends Command
{
    // the name of the command (the part after "bin/console")
    protected static $defaultName = 'app:run-example';
    
    // 2. Expose the EntityManager in the class level
    private $entityManager;

    public function __construct(EntityManagerInterface $entityManager)
    {
        // 3. Update the value of the private entityManager variable through injection
        $this->entityManager = $entityManager;

        parent::__construct();
    }
    
    protected function configure()
    {
        // ...
    }

    // 4. Use the entity manager in the command code ...
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $em = $this->entityManager;
        
        // A. Access repositories
        $repo = $em->getRepository("App:SomeEntity");
        
        // B. Search using regular methods.
        $res1 = $repo->find(1);
        $res2 = $repo->findBy(['field' => 'value']);
        $res3 = $repo->findAll();
        $res4 = $repo->createQueryBuilder('alias')
            ->where("alias.field = :fieldValue")
            ->setParameter("fieldValue", 123)
            ->setMaxResults(10)
            ->getQuery()
            ->getResult();
        
        // C. Persist and flush
        $em->persist($someEntity);
        $em->flush();
         
        return 0;
    }
}

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors