php-从Laravel作业中调用Laravel命令

我有一个名为MyCommand的命令,我是从一个名为MyJob的作业中调用它的.从job调用时,我看不到命令​​输出.但是,如果我直接从命令行运行命令,则会看到命令输出.

MyCommand.php代码:

namespace App\Console\Commands;

use Illuminate\Console\Command;

class MyCommand extends Command
{

    protected $signature = 'mycommand:doit';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $this->info('Process started');

        //Some process is done here

        $this->info('Process completed');
    }
} 

MyJob.php代码:

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Artisan;

class MyJob implements ShouldQueue
{
    public function __construct()
    {

    }

    public function handle()
    {
        Artisan::call('mycommand:doit');
    }
} 

解决方法:

从理论上讲,您不是在终端上运行作业(例如,可能正在排队或安排工作),在终端外运行时不会保存输出.

但是,您仍然可以使用Artisan :: output();获得输出缓冲区.

例:

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Artisan;

class MyJob implements ShouldQueue
{
    public function __construct()
    {

    }

    public function handle()
    {
        Artisan::call('mycommand:doit');
        $output = Artisan::output(); // $output is a string

        // Do whatever you want with $output
    }
}

更新:同步输出

您可以尝试以下方法:
命令示例:

class SlowCommand extends Command
{
    protected $signature = "slow";


    public function handle()
    {
        $max = 10;

        for ($i = 0; $i < $max; $i++) {
            $this->line($i);
            sleep(1);
        }
    }
}
// Synchronous output
Artisan::call("slow"); 
echo Artisan::output();

// Asynchronous output
$buffer = new ConsoleOutput();
Artisan::call("slow", [], $buffer);
上一篇:Linxu 后台运行


下一篇:集成学习-幸福感案例分析1