2016-03-31 46 views
0

是否可以在Laravel的控制器中運行composer或git命令?類似的東西:Laravel在控制器內運行作曲家/ git命令

class TestController extends Controller 
{ 
    // 
    public function shell(Request $request){ 
     if($request->isMethod('post')){ 


      $data['output'] = shell_exec('composer update'); 
      // or some git commands 
      return view('tests.shell', $data); 
     } else { 
      return view('tests.shell'); 
     } 
    } 
} 

如果按照上面顯示的方式,我不會收到任何消息。我認爲,問題是,這些命令必須在項目根目錄中運行,而不是在子文件夾中運行。

是否有一個PHP函數來運行一個完整的shell腳本,而不僅僅是單個命令?

我測試了這一點:

echo shell_exec('php ' . __DIR__ . '/../shell.php'); 
// shell.php is in projects root directory 

執行腳本,而不是在根目錄下。

謝謝!

回答

1

我還沒有注意到它,但Laravel附帶了一個工具來運行終端命令/作曲家命令。您可以使用Symfony的The Process Component。所以運行命令變得非常簡單。

爲Laravel 5.2的一個例子:

namespace App\Http\Controllers; 

use Illuminate\Database\Eloquent\ModelNotFoundException; 
use Illuminate\Http\Request; 

use App\Http\Requests; 

use Symfony\Component\Process\Process; 
use Symfony\Component\Process\Exception\ProcessFailedException; 

class SetupController extends Controller 
{ 
    public function setup(){ 
     $migration = new Process("php artisan migrate"); 

     $migration->setWorkingDirectory(base_path()); 

     $migration->run(); 

     if($migration->isSuccessful()){ 
      //... 
     } else { 
      throw new ProcessFailedException($migration); 
     } 
    } 
} 
1

你可以嘗試這樣的事情:

$data['output'] = shell_exec('(cd '. base_path() .' && /usr/local/bin/composer info)'); 

// debug 
dd($data); 

的命令是在()讓我們模式的根文件夾如果項目和執行composer info

下面的git命令也能過,但沒有git pullgit fetch

$data['output'] = shell_exec('(cd '. base_path() .' && /usr/bin/git status)') 

我也試過/usr/local/bin/composer update命令,但你必須等待包來更新腳本或者返回null或超時。

其值得指出的是應該使用composer/git的完整路徑,即/usr/local/bin/composer,否則您將會一直看到返回的null

對於你的PHP腳本,嘗試類似的東西:

echo shell_exec('(cd '. base_path() .' && php shell.php)'); 

編輯

如果你想登錄命令的輸出到文件,並試圖在PHP中捕捉到,你可以嘗試:

$data['output'] = shell_exec('(cd '. base_path() .' && /usr/bin/git status | tee -a file.log)') 

tee -a file.log部分將輸出保存到file.log以及輸出到屏幕(因此shell_exec可以拾取輸出),並且-a標誌將在文件已經存在的情況下追加新的輸出(如果您希望有一個歷史記錄爲先前的命令)。

+0

一切都在我的本地環境中正常工作。但我的laravel安裝沒有成功。結果是NULL。我也試圖執行比composer/git(例如php artisan make:controller XyzController)的其他命令,但沒有成功... – Brotzka

+0

我也有混合的結果。一些命令完美工作,而其他命令則返回'''null'''。可能與命令生成的輸出類型有關或PHP超時... –

+0

您知道一種記錄操作的方法嗎?當沒有輸出時,很難檢查命令是否成功^^ – Brotzka