ThinkPHP6.0自定义命令行指令需继承think\console\Command,置于app/command/下,实现configure()设命令名及参数、execute()写逻辑,调用$this->app->initialize()初始化上下文,修改后执行php think clear清缓存。

ThinkPHP6.0 自定义命令行指令,核心是写一个继承 think\console\Command 的类,放在 app/command/ 目录下,实现 configure() 和 execute() 两个方法,注册后清缓存即可使用。
创建命令类文件
文件必须放在 app/command/ 目录下(不能放子目录),命名空间为 app\command,类名建议以 Command 结尾(如 SyncUserCommand),文件名与类名严格一致(SyncUserCommand.php)。
- 继承基类:
use think\console\Command; - 必须实现
configure()方法,并在其中调用$this->setName('sync:user')—— 命令名只允许小写字母、数字、冒号和短横线 - 必须实现
execute(Input $input, Output $output)方法,所有业务逻辑写在这里 - 不要写
handle(),TP6 不识别该方法
声明参数与选项
参数和选项必须在 configure() 中提前注册,运行时才可解析。未声明的参数会被忽略。
- 添加必填参数:
$this->addArgument('id', Argument::REQUIRED, '用户ID') - 添加可选选项:
$this->addOption('force', 'f', Option::VALUE_NONE, '强制执行') - 获取参数:
$input->getArgument('id') - 判断选项:
$input->hasOption('force'),取值:$input->getOption('force')
在命令中安全使用模型和数据库
命令执行时应用上下文默认未初始化,直接调用 Db:: 或 UserModel:: 会报 No application initialized 错误。
立即学习“PHP免费学习笔记(深入)”;
- 在
execute()开头加一行:$this->app->initialize(); - 推荐用容器获取对象:
$this->app->db替代全局Db::,$this->app->model(UserModel::class)替代 new 实例 - 避免手动 new 模型,否则事件、验证器等扩展功能失效
注册与生效
TP6 默认启用自动发现机制,只要类满足规范,一般无需手动注册。但要注意:
- 确认
app/command.php返回的是空数组return [];,避免覆盖自动扫描 - 若手动注册,格式为:
['sync:user' => app\command\SyncUserCommand::class],键是命令名,值是字符串类名 - 每次修改后必须运行
php think clear清除命令缓存,否则php think list看不到新命令 - 执行测试:
php think sync:user 123 --force



















