2017-08-25 28 views
1

我試圖從另一個命令調用一個Artisan(Laravel)命令。不過,我需要能夠檢索從由「主」命令調用命令的陣列...從一個Artisan命令返回到另一個的值

// Command 1 
public function handle() { 
    $returnedValue = $this->call('test:command'); 

    dump($returnedValue); // <-- is 5 

} 

// Command 2 
public function handle() { 
    return $this->returnValue(); 

} 

private function returnValue() { 
    $val = 5; 
    return $val; 
} 

我已經通過文件看,並不能找到一個這樣做的方式,所以我想知道是否有辦法或如果我需要重新考慮我的方法。

謝謝!

回答

1

Artisan命令的行爲與控制器功能的行爲不同。他們返回一個exitCode,在我的測試中,它總是0(如果發生錯誤,則無法返回任何內容)。

如果您嘗試獲取返回值,但您可以訪問\Artisan::output();以查看您調用的第一個artisan命令發送了什麼,否則您的方法將不起作用。

// FirstCommand.php 
public function handle(){ 
    \Artisan::call("second:command"); 
    if(\Artisan::output() == 1){ 
    $this->info("This Worked"); 
    } else { 
    $this->error("This Didn't Work"); 
    } 
} 

注:我用\Artisan::call();兩個使用$this->call()不符合預期,但\Artisan::call()做了一些明顯的區別。 $this->call()發回01,不管正在執行的實際代碼是什麼;不知道那裏有什麼。在Laravel 5.0上測試,這是相當落後的,所以也許就是這樣。

// SecondCommand.php 
public function handle(){ 
    try { 
    $test = 1/1; 
    } catch (\Exception $ex){ 
    $this->error("0"); 
    } 

    $this->info("1"); 
} 

運行php artisan first:command在我的控制檯回報:

$ PHP工匠第一:命令

這個工作

現在,如果在$test代碼切換到

$test = 1/0; 

我得到這個在我的控制檯:

$ PHP工匠第一:命令

這並不工作

所以,在這裏我想規則是爲了避免任何輸出第二個命令在你想要檢查的結果之前\Artisan::output()

相關問題