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 = [AppConsoleCommandsSendDailyReport::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 应用更易于维护和自动化。
以上就是 Laravel 框架怎么使用命令行 工具 _Laravel Artisan 命令自定义开发的详细内容,更多请关注php 中文网其它相关文章!


