Laravel的Artisan可创建自定义命令处理后台任务;2. 使用make:command生成命令类,定义signature和description属性;3. 在handle()中编写逻辑并获取参数与选项;4. 将命令类添加到app/Console/Kernel.php的$commands数组中注册;5. 可通过php artisan调用命令,支持参数、选项及交互确认;6. 在Kernel.php的schedule()中配置定时执行,结合Cron实现自动化。

Laravel 提供了一个强大的命令行工具叫 Artisan,它能帮助开发者快速生成代码、运行任务、管理应用。除了使用内置命令外,Laravel 还支持自定义 Artisan 命令,让你可以封装常用逻辑,通过命令行高效执行。
创建自定义 Artisan 命令
要创建一个自定义命令,使用以下 Artisan 命令:
artisan make:command SendDailyReport这会在 app/Console/Commands 目录下生成一个名为 SendDailyReport.php 的类文件。
生成的类包含两个主要属性和方法:
- $signature:定义命令名称和参数格式
-
$description:描述命令用途,显示在
php artisan list中 - handle():命令执行时调用的核心逻辑
示例:定义一个带参数的命令
protected $signature = 'report:send {user} {--queue}';protected $description = '发送每日报告给指定用户';
在 handle() 方法中获取参数:
public function handle() { $user = $this->argument('user'); $queue = $this->option('queue');if ($queue) {
// 加入队列处理
dispatch(new SendReportJob($user));
} else {
// 立即发送
$this->info("正在发送报告给用户: $user");
}}
注册自定义命令
新创建的命令需要在 app/Console/Kernel.php 中注册才能使用。
打开该文件,在 $commands 数组中添加你的命令类:
protected $commands = [ \App\Console\Commands\SendDailyReport::class, ];注册后,运行 php artisan list 就能看到你的命令出现在列表中。
使用命令参数与选项
Artisan 支持接收参数和选项,让命令更灵活。
-
{user}:必需参数,通过
argument('user')获取 - {user?}:可选参数
- {--queue}:布尔选项,是否存在
- {--delay=5}:带默认值的选项
你还可以使用交互式提问:
if ($this->confirm('确定要发送吗?')) { $this->info('开始发送...'); }调度自定义命令(可选)
如果希望命令定时执行,可在 app/Console/Kernel.php 的 schedule() 方法中配置:
$schedule->command('report:send admin --queue') ->dailyAt('08:00');然后只需在服务器添加一条 Cron 条目:
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1基本上就这些。自定义 Artisan 命令适合处理数据清理、邮件推送、定时同步等后台任务,让 Laravel 应用更易于维护和自动化。










