在项目开发过程中,为了方便,我们可能需要自定义一个属于自己的 artisan 命令执行特殊的任务.
那么如果在 Laravel 中如何新建一个属于自己的 artisan 命令呢?
1. 生成命令类
php artisan 命令可以列出所有可用的 artisan 命令,其中有一个命令是 artisan make command
make command 命令是用来生成自定义命令类的.现在我们用这个命令来生成一个自己的命令类
php artisan make:command DemoCommandTest --command=demo:test:nwei
DemoCommandTest 是新建的命令类, demo:test:nwei 是我们自定义的命令
我们修改我们的命令类如下:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
class DemoCommandTest extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'demo:test:nwei';
/**
* The console command description.
*
* @var string
*/
protected $description = '这个一个新的命令类,自定义的哦';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
//
$this->info("开始执行....");
Log::info("逻辑代码在这里....");
$this->info("执行结束...");
}
}
description 是命令描述.可以修改.
handle() 是主方法,所有的逻辑都在 handle() 方法中.
2. 执行 artisan
执行 php artisan 可以看到刚才新建的命令,如下:
执行我们的自定义命令
laravel.log 文件中多了一条记录
这就是如何在 laravel 中自定义自己的 artisan 命令.