2017-12-27 401 views
0

我想从我的控制器使用过程组件运行控制台命令,但它不起作用。从控制器的Symfony3控制台运行控制台命令

这是我的代码:

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

我也试过:

php bin/console mycommand:run my_argument 

你能告诉我什么,我做错了:

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

我使用运行我的命令?

+0

“不起作用”是什么意思?有没有错误信息? –

回答

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调用命令。

+0

我之前尝试过这种方法,并且解决了问题,但我也希望能够在运行后停止该命令。通过Process,我可以在某个地方回收pid,然后杀死该进程。如果我能杀死命令,我可以用pcntl_signals获得这个解决方案的选择是什么,但正如你可以在我之前的线程中看到的 - https://stackoverflow.com/questions/47941237/symfony3-command- pcntl-doesnt-works 它没有为我工作。 – SakuragiRokurota

+0

@SakuragiRokurota你最好的选择是使用消息队列。这样你的控制器只向队列发送消息,命令处理将从HTTP请求中分离出来。 – svgrafov