Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 4: doctrine in command

I am using symfony 4 and I want to access a repository for an entity if I am in the Command class. There is not a function getDoctrine or something..

I have created an Entity through the console, so I got an entity and a repository.

Does anybody know how I can access the repository?

like image 332
T. de Jong Avatar asked Jan 12 '18 21:01

T. de Jong


2 Answers

The official Symfony 4 advice is to autowire only what you need. So instead of injecting ContainerInterface and requesting an EntityManager from that, inject EntityManagerInterface directly:

use Doctrine\ORM\EntityManagerInterface;

class YourCommand extends Command
{

    private $em;

    public function __construct(EntityManagerInterface $em)
    {
        parent::__construct();
        $this->em = $em;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->em->persist($thing);
        $this->em->flush();
    }

}
like image 147
Jamie McLaughlin Avatar answered Sep 20 '22 11:09

Jamie McLaughlin


The best practice is to delegate this task to a service. See this example: https://symfony.com/doc/current/console.html#getting-services-from-the-service-container

However you can also add a constructor to the command and give it a ContainerInterface. Then you just do $this->container->get('doctrine')->getManager();

// YourCommand.php

private $container;

public function __construct(ContainerInterface $container)
{
    parent::__construct();
    $this->container = $container;
}

protected function execute(InputInterface $input, OutputInterface $output)
{
    $em = $this->container->get('doctrine')->getManager();

    // do stuff...
}

Also, don't forget to add the proper "use" statement at the beggining of your script:

use Symfony\Component\DependencyInjection\ContainerInterface;
like image 39
Bloops Avatar answered Sep 18 '22 11:09

Bloops