1
1

More than 3 years have passed since last update.

Laravelのclear系コマンドを集めたArtisanコマンドを作成したい

Posted at

はじめに

LaravelのArtisanコマンドでクリア系のコマンドを実施する時、毎回下記の様に行っている。

php artisan route:clear
php artisan cache:clear
php artisan config:clear
php artisan view:clear

上記を一つにまとめられたらいいなぁ・・・と常々思っていたので、
まとめることにする。

コマンド生成

php artisan make:command all-clear

これでapp/Console/Commands配下にall-clear.phpが作成される。

名前は全部消すということでall-clearとする。
また、php artisan listでその他のコマンドを確認すると、2単語以上のコマンドはケバブケースになっていることが判明したためそれに合わせる。

  clear-compiled       Remove the compiled class file
  dump-server          Start the dump server to collect dump information.

ファイルの中身

all-clear.php
namespace App\Console\Commands;

use Illuminate\Console\Command;

class allClear extends Command
{
    /**
     * コンソールコマンドの名前と引数、オプションを記述します。
     *
     * @var string
     */
    protected $signature = 'all-clear';

    /**
     * コンソールコマンドの説明を記述します。
     *
     * @var string
     */
    protected $description = 'route cache view config全てをclearする';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
       //Artisanファサードのcallメソッドで4種類のコマンドを呼び出し、
       //戻り値を変数に格納します。
        $config = \Artisan::call('config:clear');
        $route = \Artisan::call('route:clear');
        $view = \Artisan::call('view:clear');
        $cache = \Artisan::call('cache:clear');

        //成功した場合戻り値が0、失敗した場合-1が返ってきます。
        //this->info()はコマンドラインにに出力される文字列を指定できます。
        //もっとマシな書き方があると思います。

        if (0 == $config )
        {
            $this->info('Configuration cache cleared!');
        }
        if (0 == $route )
        {
            $this->info('Route cache cleared!');
        }
        if (0 == $view )
        {
            $this->info('Compiled views cleared!');
        }
        if (0 == $cache )
        {
            $this->info('Application cache cleared!');
        }
    }
}

実行

$ php artisan all-clear

Configuration cache cleared!
Route cache cleared!
Compiled views cleared!
Application cache cleared!

//成功しました。

終わりに

もっと良いやり方があると思います。

参考

Laravel 5.5公式リファレンス

1
1
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
1
1