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

Bro*_*zka 0 php shell cmd composer-php laravel-5

是否可以在 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');
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我按照上面显示的方式进行操作,则不会收到任何消息。我认为,问题是,这些命令必须在项目根目录中运行,而不是在子文件夹中。

是否有一个 php 函数可以运行完整的 shell 脚本而不仅仅是单个命令?

我已经测试过这个:

echo shell_exec('php ' . __DIR__ . '/../shell.php');
// shell.php is in projects root directory
Run Code Online (Sandbox Code Playgroud)

脚本被执行,但不在根目录中。

谢谢!

Bro*_*zka 8

我以前没有注意到它,但 Laravel 附带了一个工具来运行终端命令/composer 命令。您可以使用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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)