从 Laravel 作业调用的 Laravel 命令

Umu*_*GÖZ 5 php jobs command laravel laravel-artisan

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

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');
    }
} 
Run Code Online (Sandbox Code Playgroud)

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');
    }
} 
Run Code Online (Sandbox Code Playgroud)

Mat*_*our 5

理论上,您运行作业时并不在终端中(例如,作业可能已排队或计划),在终端外运行时不会保存输出。

但是,您仍然可以使用 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
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:同步输出

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

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
    }
}
Run Code Online (Sandbox Code Playgroud)
// Synchronous output
Artisan::call("slow"); 
echo Artisan::output();

// Asynchronous output
$buffer = new ConsoleOutput();
Artisan::call("slow", [], $buffer);
Run Code Online (Sandbox Code Playgroud)


Vit*_*lii 0

使用Artisan::output方法获取Artisan外观最后执行的命令的输出。