You cannot use getContainer because your command class is not aware of the container.
Make your command extend ContainerAwareCommand
So that you can use getContainer()
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
Then extends ContainerAwareCommand :
class MyCommand extends ContainerAwareCommand
And then use it wherever you want :
$em = $this->getContainer()->get('doctrine')->getManager('default');
EDIT thanks to @tomáš-votruba :
HOWEVER ContainerAware is deprecated in Symfony 4:
Using the EntityManager by injecting it :
So instead of forcefully getting the entity manager with the container, inject in your constructor instead and extend Command by using your command as a service:
namespace App\Command;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\Console\Command\Command;
class MyCommand extends Command {
//add $entityManager attribute
private $entityManager;
public function __construct(ObjectManager $entityManager)
{
$this->entityManager= $entityManager;
// you *must* call the parent constructor
parent::__construct();
}
As you can see in the constructor, we are injecting the entityManager with ObjectManager which is an interface whereas EntityManager is its ORM implementation, you can do it if you use the default services.yml or one that is set up for autowiring :
# config/services.yaml
services:
# default configuration for services in *this* file
_defaults:
autowire: true # Automatically injects dependencies in your services.
autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
public: false # Allows optimizing the container by removing unused services; this also means
# fetching services directly from the container via $container->get() won't work.
# The best practice is to be explicit about your dependencies anyway.