Symfony2 - How to access the service in a custom console command?

风流意气都作罢 提交于 2019-11-29 04:10:34

In order to be able to access the service container your command needs to extend Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand.

See the Command documentation chapter - Getting Services from the Container.

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
// ... other use statements

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

Since Symfony 3.3 (May 2017) you can use Dependency Injection in commands with ease.

Just use PSR-4 services autodiscovery in your 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(); 
    }
}

This will (or already did, depends of time reading) become standards since Symfony 3.4 (November 2017), when commands will be lazy loaded.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!