How can i inject dependencies to Symfony Console commands? How can i inject dependencies to Symfony Console commands? symfony symfony

How can i inject dependencies to Symfony Console commands?


Since Symfony 4.2 the ContainerAwareCommand is deprecated. Use the DI instead.

namespace App\Command;use Symfony\Component\Console\Command\Command;use Doctrine\ORM\EntityManagerInterface;final class YourCommand extends Command{    /**     * @var EntityManagerInterface     */    private $entityManager;    public function __construct(EntityManagerInterface $entityManager)    {        $this->entityManager = $entityManager;        parent::__construct();    }    protected function execute(InputInterface $input, OutputInterface $output)    {        // YOUR CODE        $this->entityManager->persist($object1);        }}


use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;

Extends your Command class from ContainerAwareCommand and get the service with $this->getContainer()->get('my_service_id');


It is best not to inject the container itself but to inject services from the container into your object. If you're using Symfony2's container, then you can do something like this:

MyBundle/Resources/config/services (or wherever you decide to put this file):

...    <services>        <service id="mybundle.command.somecommand" class="MyBundle\Command\SomeCommand">        <call method="setSomeService">             <argument type="service" id="some_service_id" />        </call>        </service>    </services>...

Then your command class should look like this:

<?phpnamespace MyBundle\Command;use Symfony\Component\Console\Command\Command;use Symfony\Component\Console\Input\InputArgument;use Symfony\Component\Console\Input\InputInterface;use Symfony\Component\Console\Input\InputOption;use Symfony\Component\Console\Output\OutputInterface;use The\Class\Of\The\Service\I\Wanted\Injected;class SomeCommand extends Command{   protected $someService;   public function setSomeService(Injected $someService)   {       $this->someService = $someService;   }...

I know you said you're not using the dependency injection container, but in order to implement the above answer from @ramon, you have to use it. At least this way your command can be properly unit tested.