Web 之外的活儿(定时任务、数据迁移、批量处理)交给命令行。官方手册《命令行》一章下设多个子类:命令行入口与配置、创建自定义命令、参数与选项、输出交互、内置指令。本文逐一整理,结尾附综合小实例。参考:ThinkPHP 8 命令行。
一、命令行入口与配置
php think # 列出所有可用指令
php think help run # 查看某指令的帮助
自定义指令注册在 config/console.php:
return [
'commands' => [
'hello' => appcommandHello::class,
],
];
二、创建自定义命令
用生成器创建命令类骨架:
php think make:command hello appcommandHello
生成的 app/command/Hello.php 两个方法各管一事:configure() 定义名称说明,execute() 写业务:
<?php
namespace appcommand;
use thinkconsoleCommand;
use thinkconsoleInput;
use thinkconsoleOutput;
class Hello extends Command
{
protected function configure()
{
$this->setName('hello')
->setDescription('Say Hello World');
}
protected function execute(Input $input, Output $output)
{
$output->writeln('Hello, ThinkPHP 8!');
}
}
注册后运行:php think hello。
三、参数与选项
命令支持参数(位置参数)和选项(--xxx 开关):
use thinkconsoleinputArgument;
use thinkconsoleinputOption;
protected function configure()
{
$this->setName('backup')
->addArgument('table', Argument::REQUIRED, '要备份的表')
->addOption('path', null, Option::VALUE_OPTIONAL, '保存路径', '/tmp');
}
protected function execute(Input $input, Output $output)
{
$table = $input->getArgument('table');
$path = $input->getOption('path');
}
php think backup article --path=/data
- 参数模式:REQUIRED(必填)、OPTIONAL(选填)、IS_ARRAY(多个)
- 选项模式:VALUE_NONE(开关)、VALUE_OPTIONAL、VALUE_REQUIRED,第四个参数设默认值
四、输出与交互
$output->writeln('普通输出');
$output->writeln('<info>成功信息</info>'); // 绿色
$output->writeln('<comment>提示信息</comment>'); // 黄色
$output->writeln('<error>错误信息</error>'); // 红底
用输出标签让终端信息分色,脚本日志一眼看清成功/警告/失败。
五、内置指令速查
| 指令 | 作用 |
|---|---|
php think list | 列出全部指令 |
php think help 指令名 | 查看指令帮助 |
php think run | 启动内置开发服务器 |
php think clear | 清除缓存 |
php think make:command | 生成命令类 |
php think make:controller | 生成控制器 |
php think make:model | 生成模型 |
自定义命令非常适合挂计划任务:crontab 里定时执行 php think xxx,实现数据备份、缓存预热、对账等自动化。
六、综合小实例:日志清理命令
把命令定义、参数选项、输出、计划任务串起来:
<?php
namespace appcommand;
use thinkconsoleCommand;
use thinkconsoleInput;
use thinkconsoleOutput;
use thinkconsoleinputArgument;
use thinkconsoleinputOption;
class LogClear extends Command
{
protected function configure()
{
$this->setName('log:clear')
->addArgument('days', Argument::OPTIONAL, '保留天数', 7)
->addOption('dry', null, Option::VALUE_NONE, '只预览不删除');
}
protected function execute(Input $input, Output $output)
{
$days = (int) $input->getArgument('days');
$dry = (bool) $input->getOption('dry');
// 扫描 runtime/log 删除 N 天前的日志(示例)
$output->writeln("清理 {$days} 天前的日志" . ($dry ? '(预览模式)' : ''));
$output->writeln('<info>完成</info>');
}
}
# 每天凌晨 2 点清理 7 天前日志
0 2 * * * cd /www/wwwroot/project && php think log:clear 7 >> /dev/null 2>&1
一个命令用齐了参数(days)、选项(--dry)、分色输出和 crontab 集成 —— 本章要点全覆盖。
七、总结
php think 进入命令行;make:command 生成骨架、configure 定义元信息、execute 写业务;addArgument/addOption 加参数选项,getArgument/getOption 取值;writeln 分色输出;定时需求挂 crontab 执行 php think。