ThinkPHP自动执行数据库清理等任务需创建自定义Command类,置于app/command/目录,继承think\console\Command,命名空间为app\command,类名以Command结尾,注册后清缓存生效。

想让ThinkPHP自动执行数据库清理、日志归档或百万级数据批量更新,又不想卡在Web请求超时里?直接写个命令行指令,用php think就能跑,还能塞进crontab定时触发。
创建自定义Command类文件
在项目根目录下新建文件 app/command/SyncUserCommand.php,确保路径和文件名完全匹配——框架只扫描 app/command/ 目录,且不识别子目录(如 app/index/command/)。
文件内容必须以 app\command 命名空间开头,类名以 Command 结尾,且继承 think\console\Command:
```php
<?php
namespace app\command;
use think\console\Command;
use think\console\Input;
use think\console\Output;
class SyncUserCommand extends Command
{
protected function configure()
{
$this->setName('sync:user')
->setDescription('同步用户ID字段到关联表');
}
protected function execute(Input $input, Output $output)
{
$this->app->initialize(); // 必须加!否则Db::或模型调用报“No application initialized”
$output->writeln('开始同步...');
// 此处写你的业务逻辑
$output->writeln('同步完成');
}
}
```
立即学习“PHP免费学习笔记(深入)”;
注意:类名是 SyncUserCommand,文件名必须是 SyncUserCommand.php;若写成 SyncUser.php 或 syncusercommand.php,框架将完全忽略该类。
注册命令并生效
ThinkPHP 6.0+ 默认启用自动发现机制,只要类放在 app/command/ 下、继承正确、命名规范,就无需额外注册——但前提是 application/command.php 文件不能存在,或必须返回空数组。
如果项目中已有 application/command.php,请立即检查其内容:
✅ 正确写法(启用自动发现):
```php
<?php
return [];
```
❌ 错误写法(会关闭自动发现,且格式错则命令消失):
```php
<?php
return ['app\command\SyncUserCommand']; // 缺少键名,框架无法映射命令名
```
修改后必须清缓存:php think clear,否则旧的命令列表仍被读取,新命令不会出现在 php think list 中。
添加参数与选项
方法一:支持必填参数(如指定批次大小)
在 configure() 中加入:
$this->addArgument('batch', Argument::REQUIRED, '每批处理条数');
在 execute() 中获取:
$batch = (int) $input->getArgument('batch');
调用方式:php think sync:user 5000
方法二:支持可选开关(如跳过验证)
在 configure() 中加入:
$this->addOption('skip-check', null, Option::VALUE_NONE, '跳过数据一致性校验');
在 execute() 中判断:
if ($input->hasOption('skip-check')) { /* 执行跳过逻辑 */ }
调用方式:php think sync:user --skip-check
⚠️ 不声明就传参会直接报错:“The “batch” argument does not exist.”——ThinkPHP 不允许运行时解析未声明的参数。
安全接入数据库与模型
第一步:execute() 开头必须执行 $this->app->initialize(),否则 Db::table()、UserModel::find() 等静态调用全部失败。
第二步:优先使用容器注入实例,而非 new UserModel() —— 否则事件、验证器、软删除等全失效。
推荐写法:
$userModel = $this->app->model('app\model\UserModel');
$users = $userModel->where('status', 1)->select();
第三步:大任务需手动设内存限制,避免OOM中断:
ini_set('memory_limit', '2048M');
这一步操作起来很简单,直接把 ini_set 放在 execute() 最前面就行。
部署到 crontab 定时运行
第一步:确认 crontab 运行用户对项目根目录有读取权限,尤其要能读取 .env 和 runtime/ 目录。
第二步:在服务器上编辑 crontab:
crontab -e
第三步:添加一行(以每天凌晨2点执行为例):
0 2 * * * cd /var/www/myproject && /usr/bin/php think sync:user > /dev/null 2>&1
⚠️ 关键点:cd /path/to/project && php think 必须组合使用,不能只写绝对路径的 php;否则 vendor/autoload.php 找不到,直接 Fatal error。
第四步:保存退出后,等待 cron 触发,或手动运行该行命令测试输出是否正常。



















