Laravel5.1 自定義Artisan命令


如果我們想生成自己的artisan命令 首先在cd到項目目錄生成console:

php artisan make:console TestArtisan

這行命令就會生成一個名為 TestArtisan 的console,我們在這個目錄就可以找到它:app\Console\Commands:

class TestArtisan extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:name';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
    }
}

 

自定義命令

$signature 這個變量就是我們在命令行中輸入的命令 比如make:controller,make:model等,我們將它改為我們想要的命令:

    protected $signature = 'learn_laravel:console';

$description這個變量沒有什么好說的,就是說明:

    protected $description = 'learn how to customize commands';

具體的業務邏輯是定義在handle方法中的,我們先來定義簡單的打印一串文字:

    public function handle()
    {
        $this->info('test Hello');
    }

最后一步就是將這個console注冊,我們在app\Console\Kernal.php文件中注冊:

    protected $commands = [
        \App\Console\Commands\Inspire::class,
        // 注冊我們自己的命令
        \App\Console\Commands\TestArtisan::class,
    ];

如何查看我們有沒有注冊成功呢?我們使用 php artisan 命令就會看到一大堆的命令,這其中如果包含了我們自定義的artisan,那么就注冊成功了。

我們現在可以使用我們自定義的命令來測試了:

php artisan learn_laravel:console

 

傳入參數

在諸多的artisan命令中 我們常常會傳入一些參數 比如:php artisan make:model Articles。那么如何傳入參數呢?我們來修改下$signature:

    protected $signature = 'learn_laravel:console {arguments}';

沒錯,只需要添加一個{}里面跟上參數名就可以了。

 

我們可以在handle方法中接收參數:

    public function handle()
    {
        $this->info('test Hello '.$this->argument('arguments'));
    }

 

可選參數

當我們指定了參數后就必須傳入參數,在有些時候參數是可以不設置的,那么我們需要這么寫:

    protected $signature = 'learn_laravel:console {arguments?}';
    public function handle()
    {
        $this->info('test Hello '.$this->argument('arguments'));
    }

這樣就不會報錯了。

 

默認參數

如果指定了默認參數值,當傳入參數后使用傳入后的參數,沒有指定則使用默認值:

    protected $signature = 'learn_laravel:console {arguments=default}';

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM