PHP   发布时间:2022-04-04  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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);

大佬总结

以上是大佬教程为你收集整理的php-从Laravel作业中调用Laravel命令全部内容,希望文章能够帮你解决php-从Laravel作业中调用Laravel命令所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: