2017-12-27 398 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