簡體   English   中英

Laravel在控制器中運行composer / git命令

[英]Laravel run composer / git commands within controller

在Laravel的控制器中可以運行composer或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

該腳本已執行,但不在根目錄中。

謝謝!

我以前沒有注意到它,但是Laravel附帶了一個運行終端命令/合成程序命令的工具。 您可以使用Symfony中的過程組件 因此,運行命令變得非常容易。

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);
        }
    }
}

您可以嘗試如下操作:

$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標志會將新輸出附加到文件(如果已存在的話)(如果需要)具有一個包含先前命令歷史記錄的日志文件)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM