Laravel - 在当前服务器上执行控制台命令

时间:2016-09-08 08:05:04

标签: laravel laravel-5.2

请解释一下。如何从我的控制器执行命令行命令。

例如我想启动icecast服务器

当然我可以使用exec('icecast2 run -c path/to/config.xml')

Laravel是否有办法做到这一点?

1 个答案:

答案 0 :(得分:1)

macro中创建Envoy.blade.php,了解详情:https://laravel.com/docs/5.2/envoy

@macro('deploy')
    //your commands here
@endmacro

哟可以通过Symfony进程(http://symfony.com/doc/current/components/process.html#usage)调用它,如下所示:

$process = new Process("/home/$user/.composer/vendor/bin/envoy run deploy");
$process->setTimeout(3600);
$process->setIdleTimeout(300);
$process->setWorkingDirectory(base_path());
$process->run(function ($type, $buffer)
{
    //print output
});

为此创建一些外部类更好。

<?php

namespace App\Services;

use Symfony\Component\Process\Process;

class Envoy
{

public function run($task, $live = false)
{
    $result = [];

    $process = new Process('~/.composer/vendor/bin/envoy run '. $task);
    $process->setTimeout(3600);
    $process->setIdleTimeout(300);
    $process->setWorkingDirectory(base_path());
    $process->run(
        function ($type, $buffer) use ($live, &$result) {
            $buffer = str_replace('[127.0.0.1]: ', '', $buffer);

            if ($live) {
                echo $buffer . '</br />';
            }

            $result[] = $buffer;
        }
    );

    return $result;
}
}

从控制器调用它:

public function store(Request $request, Envoy $envoy)
{
    $group = $this->group->create($request->all());

    $result = $envoy->run('<some command>');

    // Do something with $result...
}

致谢:https://laracasts.com/discuss/channels/general-discussion/run-envoy-from-controller