在侦听器中调用命令

时间:2018-03-09 13:56:23

标签: symfony events command listener

我的symfony API中有一个非常复杂的命令(不是由我编写)来发送通知,我希望每次发生PostPersist事件时都会运行它。

为此,我设置了一个由PostPersist事件触发的监听器,这部分工作正常。但是,我无法启动命令。我首先尝试使用以下代码在控制器中启动它:

$kernel = $this->get('kernel');
$application = new Application($kernel);
$application->setAutoExit(false);

$input = new ArrayInput(array(
    'command' => 'acme:send-notifications',
));
// You can use NullOutput() if you don't need the output
$output = new NullOutput();
$application->run($input, $output);
return new Response("");

但当然,它在Listener中不起作用,因为我无法获得内核 所以我尝试将命令添加到服务中:

command.send-notifications:
    class: WD\ApiBundle\Command\SendNotificationsCommand
    tags:
        - { name: 'console.command', command: 'acme:send-notifications' }

然后以这种方式调用它:

$output = new NullOutput();
$this->sendNotifCommand->execute(null, $output);

但后来我收到以下错误消息: The container cannot be retrieved as the application instance is not yet set.

我不得不承认我不太明白这意味着什么。此外,我必须承认symfony(听众,命令)的这一部分对我来说是一个新手,我甚至不知道我是否以正确的方式做到这一点,或者是否有更好的系统在每次持续发生时发送通知在一个特定的实体......

1 个答案:

答案 0 :(得分:0)

从未在侦听器中尝试过,但您可以尝试使用进程启动命令:

$process = new Process("cd " . $this->projectDir . "; php bin/console YOUR_COMMAND_NAME");
$process->start();