简体   繁体   English

如何将服务注入 symfony 命令?

[英]How to inject a service into a symfony command?

I have this basic Symfony command class我有这个基本的 Symfony 命令 class

class MyCommand extends Command
{

    protected EntityManagerInterface $em;

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

    protected function configure()
    {
        $this
            ->setName('my:command')
            ->setDescription('what my command does');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        echo 'Hello World';
    }

}

if I run bin/console my:command I get an error saying the command does not exists.如果我运行 bin/console my:command,我会收到一条错误消息,指出该命令不存在。

If I comment out the constructor then I can see the output. autoconfigure and autowire are set to true.如果我注释掉构造函数,那么我可以看到autoconfigureautowire设置为 true。

this is services.yml:这是服务.yml:

_defaults:
    autowire: true
    autoconfigure: true

same thing if I use如果我使用同样的事情

my_command:
        class: Path\To\MyCommand
        arguments:
            - "@doctrine.orm.entity_manager"

Looks like the way you have written your property is wrong.看起来你写你的财产的方式是错误的。 Can you change it from:你能改变它吗:

protected EntityManagerInterface $em;

to:到:

protected $em;

and try again.然后再试一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM