创建自定义Artisan命令使用php artisan make:command MyCustomCommand生成命令类,位于app/Console/Commands目录;2. 在生成的类中通过$signature定义命令名和参数格式,如必填参数{name}、可选参数{name?}、选项{--force}等;3. 使用$this->argument()和$this->option()在handle方法中获取输入值;4. 将命令类添加到app/Console/Kernel.php的$commands数组中完成注册;5. 通过$this->ask()、confirm()、choice()实现用户交互,info()、warn()、error()输出美化信息;6. 在Kernel.php的schedule()方法中配置定时任务,如dailyAt('02:00');7. 服务器crontab添加每分钟执行php artisan schedule:run以触发调度。

在Laravel中,Artisan命令行工具是开发过程中非常实用的组件。通过自定义Artisan命令,你可以将常用任务自动化,比如数据清理、定时任务预处理、数据库维护等。下面介绍如何创建和扩展自己的Artisan命令。
创建自定义Artisan命令
使用Laravel提供的生成命令可以快速创建一个新的Artisan命令类:
php artisan make:command MyCustomCommand该命令会在app/Console/Commands目录下生成一个名为MyCustomCommand.php的文件(如果目录不存在,请先创建并注册到app/Console/Kernel.php)。
打开生成的类文件,你会看到基本结构如下:
namespace App\Console\Commands;use Illuminate\Console\Command;
class MyCustomCommand extends Command { protected $signature = 'custom:run'; protected $description = '描述这个命令的作用';
public function __construct() { parent::__construct(); } public function handle() { $this->info('命令执行成功!'); }}
signature 定义了命令名称和参数格式,例如:
- custom:run —— 基础命令名
- custom:run {name} —— 接收必填参数 name
- custom:run {name?} —— 可选参数
- custom:run {--force} —— 布尔选项
- custom:run {--path=} —— 接收值的选项
在handle方法中可以通过以下方式获取输入:
- $this->argument('name') —— 获取参数值
- $this->option('force') —— 获取选项值
注册命令到Artisan
新创建的命令需要在app/Console/Kernel.php中的$commands数组里注册才能生效:
protected $commands = [
\App\Console\Commands\MyCustomCommand::class,
];
注册后就可以在终端运行:
php artisan custom:run添加交互与输出美化
Laravel提供了多种方法提升命令行体验:
- $this->ask('问题?') —— 请求用户输入
- $this->confirm('确认操作吗?') —— 是/否确认
- $this->choice('选择角色', ['admin', 'user'], 'user') —— 列出选项供选择
- $this->info('提示信息') —— 绿色文字输出
- $this->warn('警告信息') —— 黄色输出
- $this->error('错误信息') —— 红色输出
- $this->line('普通文本') —— 普通行输出
示例用法:
public function handle()
{
$name = $this->ask('你的名字是?');
if ($this->confirm('是否继续?')) {
$this->info("你好,{$name}!");
} else {
$this->warn('已取消');
}
}
调度与自动运行
如果你希望命令定期执行,可以在app/Console/Kernel.php的schedule方法中定义计划任务:
protected function schedule(Schedule $schedule)
{
$schedule->command('custom:run')->dailyAt('02:00');
}
然后在服务器的crontab中添加一行:
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1这样Laravel会每分钟检查是否有待执行的任务。
基本上就这些。自定义Artisan命令能极大提高运维效率,结合调度系统可实现全自动脚本运行,非常适合日志清理、缓存重建、数据同步等场景。










