6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Laravel コマンド(Command) 進み具合を見るプログレスバーを使って、かっこよくしてみた

Last updated at Posted at 2019-06-19

行うこと

コマンド実行時にかっこいいプログレスバーを表示したい。

まず、テスト用にCommand用のファイルを作成する。

コマンド
php artisan make command ProgressTestCommand

基本形

あまり、カスタマイズせずにプログレスバーを表示してみます。

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class ProgressTestCommand extends Command
{
    protected $signature = 'test-progress';

    protected $description = '進行状況を可視化するTest';

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

    public function handle()
    {
        $loopCount = 1000;
        $progressBar = $this->output->createProgressBar($loopCount);

        //開始
        $progressBar->start();

        for($i = 0 ; $i < $loopCount ; $i++) {
            //プログレスバーを進める
            $progressBar->advance();
        }

        //終了
        $progressBar->finish();
    }
}

実行してみます。

コマンド
root@34112e76c30c:/var/www# php artisan test-progress
 1000/1000 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%

プログレスバーがでています。

カスタムしていく

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class ProgressTestCommand extends Command
{
    protected $signature = 'test-progress';

    protected $description = '進行状況を可視化するTest';

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

    public function handle()
    {
        $loopCount = 100000;
        $progressBar = $this->output->createProgressBar($loopCount);

        // プログレスバーのフォーマット
        $progressBar->setFormat(' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%');

        // 処理前の表示
        $progressBar->setEmptyBarCharacter('|');

        // 処理後の表示
        $progressBar->setBarCharacter('-');

        // 処理中の表示
        $progressBar->setProgressCharacter(">");
        
        //開始
        $progressBar->start();

        for($i = 0 ; $i < $loopCount ; $i++) {
            //プログレスバーを進める
            $progressBar->advance();
        }

        //終了
        $progressBar->finish();
    }
}

root@34112e76c30c:/var/www# php artisan test-progress
  20471/100000 [----->||||||||||||||||||||||]  20% 6 secs/29 secs 12.0 MiB

ちょっとカッコよくなった感

まとめ

ループ処理なんかを持ったコマンドを複数実行する場合は、可視化することでよりそれっぽく見えるなーと思った。
ただ、プログレスバー用の処理はなるべくどこかにまとめておきたいと思った。

参考にさせていただいた記事

https://blog.capilano-fw.com/?p=3402
https://programmer-jobs.blogspot.com/2017/02/laravel-5-4-artisan-console-progress-bars.html

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?