0

I have the following command, which successfully prints styled messages to the bash terminal when called:

class DoSomethingCommand extends Command
{
    protected function configure()
    {
        $this->setName('do:something')
            ->setDescription('Does a thing');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $io = new SymfonyStyle($input, $output);

        $io->title('About to do something ... ');

        $io->success('Done doing something.');
    }
}

... but when I add the following in services.yml in order to try to define my command as a service ...

services:
  console_command.do_something:
    class: AppBundle\Command\DoSomethingCommand
    arguments:
      - "@doctrine.orm.entity_manager"
    tags:
      - { name: console.command }

... I get this error:

Warning: preg_match() expects parameter 2 to be string, object given in src/app/vendor/symfony/symfony/src/Symfony/Component/Console/Command/Command.php:665

What am I doing wrong here?

4

1 回答 1

3

首先,您注入服务,但您在命令中执行任何构造函数。

这意味着您当前正在将EntityManager(object) 注入到 Command 类的参数中(需要一个stringor null,这就是您遇到错误的原因)

# Symfony\Component\Console\Command\Command
class Command
{
    public function __construct($name = null)
    {

然后,按照文档中的定义,您必须调用父构造函数

class YourCommand extends Command
{
    private $em;

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

        // you *must* call the parent constructor
        parent::__construct();
    }

容器感知命令

请注意,您的课程可以扩展ContainerAwareCommand,您将能够通过$this->getContainer()->get('SERVICE_ID'). 这不是一个坏习惯,因为命令可以被视为控制器。(通常您的控制器会注入容器)

于 2018-02-22T13:19:12.690 回答