Thursday, December 7, 2017

How to access the service in a custom console command?

How to access the service in a custom console command?

You can use Dependency Injection in commands with ease since Symfony 3.3 (May 2017).

Use PSR-4 services autodiscovery in the services.yml:

services:
    _defaults:
        autowire: true

    App\Command\:
        resource: ../Command

Then use common Constructor Injection and finally even Commands will have clean architecture:

final class MyCommand extends Command
{
    /**
     * @var SomeDependency
     */
    private $someDependency;

    public function __construct(SomeDependency $someDependency)
    {
        $this->someDependency = $someDependency;

        // this is required due to parent constructor, which sets up name 
        parent::__construct(); 
    }
}

Alternative method is to extend Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand:

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;

class MyCommand extends ContainerAwareCommand
{
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $em = $this->getContainer()->get('doctrine')->getEntityManager();
    }
}

Reference:

https://stackoverflow.com/questions/19321760/symfony2-how-to-access-the-service-in-a-custom-console-command

https://www.tomasvotruba.cz/blog/2017/05/07/how-to-refactor-to-new-dependency-injection-features-in-symfony-3-3/#4-use-psr-4-based-service-autodiscovery-and-registration

http://symfony.com/blog/new-in-symfony-3-4-lazy-commands

No comments: