【问题标题】:Symfony3 console running console command from controllerSymfony3 控制台从控制器运行控制台命令
【发布时间】:2017-12-27 12:41:39
【问题描述】:

我正在尝试使用 Process Component 从我的控制器运行控制台命令,但它不起作用。

这是我的代码:

     $process = new Process('php bin/console mycommand:run');
     $process->setInput($myArg);
     $process->start();

我也试过了:

    $process = new Process('php bin/console mycommand:run ' . $myArg)
    $process->start();

我使用以下命令运行我的命令:

php bin/console mycommand:run my_argument

你能告诉我我做错了什么吗?

【问题讨论】:

  • “它不起作用”是什么意思?有错误提示吗?

标签: php symfony command


【解决方案1】:

我认为问题在于路径。无论如何,你应该考虑不使用Process 来调用 Symfony 命令。控制台组件允许调用命令,例如在控制器中。

来自文档的示例:

// src/Controller/SpoolController.php
namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelInterface;

class SpoolController extends Controller
{
    public function sendSpoolAction($messages = 10, KernelInterface $kernel)
    {
        $application = new Application($kernel);
        $application->setAutoExit(false);

        $input = new ArrayInput(array(
           'command' => 'swiftmailer:spool:send',
           // (optional) define the value of command arguments
           'fooArgument' => 'barValue',
           // (optional) pass options to the command
           '--message-limit' => $messages,
        ));

        // You can use NullOutput() if you don't need the output
        $output = new BufferedOutput();
        $application->run($input, $output);

        // return the output, don't use if you used NullOutput()
        $content = $output->fetch();

        // return new Response(""), if you used NullOutput()
        return new Response($content);
    }
}

使用这种方式,您可以确定代码将始终有效。当 PHP 处于安全模式时(exec 等已关闭)Process 组件无用。此外,您不需要关心路径和其他事情,否则您称为“手动”命令的情况。

您可以阅读有关从控制器here 调用命令的更多信息。

【讨论】:

  • 我之前尝试过这个方法,它成功了,但我也希望能够在它运行后停止该命令。使用 Process,我可以在某处检索 pid,然后终止该进程。如果我能够终止命令,我对这个解决方案有什么选择,我听说 pcntl_signals 可以,但正如你在我之前的帖子中看到的那样 - stackoverflow.com/questions/47941237/… 它对我不起作用。
  • @SakuragiRokurota 你最好的选择是使用消息队列。这样你的控制器只向队列发送消息,命令处理将与 HTTP 请求分开。
猜你喜欢
  • 1970-01-01
  • 2014-12-17
  • 2011-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 2016-02-07
相关资源
最近更新 更多