【问题标题】:Laravel command called from Laravel job从 Laravel 作业调用的 Laravel 命令
【发布时间】:2019-10-14 22:36:09
【问题描述】:

我有一个名为 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');
    }
} 

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');
    }
} 

【问题讨论】:

    标签: php laravel command jobs laravel-artisan


    【解决方案1】:

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

    但是,您仍然可以使用 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);
    

    【讨论】:

    • 这可行,但它会在命令完成时返回输出。我想在它们发生时获得实时信息、通知和错误,而不是整个命令完成。我部分地找到了一种方法来做到这一点,而不是使用 $this->info,我直接回显信息文本。
    • 是的,当然,这是一段同步的代码。但是由于您没有精确地确定 Artisan 调用的范式,所以我没有尝试实时。
    • @UmutKIRGÖZ 按照您的要求,我尝试包含异步输出。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2015-11-12
      • 2015-08-26
      • 2020-09-09
      • 2019-01-27
      • 2019-09-02
      • 1970-01-01
      • 2020-01-19
      • 2015-04-19
      • 2017-10-21
      相关资源
      最近更新 更多