thinkphp6升级需重构命名空间、配置加载、路由注册、模型调用、中间件和模板语法;90%以上tp5项目不修改代码无法运行。

ThinkPHP5升级到ThinkPHP6不是简单替换版本号,而是架构级调整。核心改动集中在命名空间、配置加载、路由注册、模型调用、中间件机制和模板语法这几个方面。不改代码直接运行,90%以上项目会报错或功能失效。
命名空间和类引用必须重写
TP6废弃所有全局短名类(如think\Controller、think\Model),全部迁移至think\facade和think\db命名空间:
- 控制器中
use think\Controller;→ 删除,或改为use think\facade\View;(仅需视图时);控制器默认继承think\controller\Base,无需手动引入 - 模型中
use think\Model;→ 改为use think\Model as BaseModel;,且模型类必须显式extends BaseModel - 数据库操作:原
Db::name('user')仍可用,但think\Db类不再作为独立入口;查询返回对象(如Collection),需调用->toArray()才能转为数组 - 助手函数如
dump()、input()保留,但底层已由think\helper\*移至think\facade\*,不建议再use助手类
配置文件结构和读取方式变了
TP6的config/目录是扁平结构,不再支持子目录嵌套,且只默认加载app.php、database.php等预设文件:
- 原
config/api.php、config/oss.php等自定义配置不会自动加载 → 需手动调用Config::load('api', 'api')显式载入 - 配置读取从
Config::get('database.type')变为Config::get('database.type')(写法相同,但路径必须完整,不能省略一级键);旧写法Config::pull('app')已废弃,统一用get -
database.php中'type' => 'MySQL'必须小写 → 改为'type' => 'mysql',否则报Driver [MySQL] not supported
路由定义必须重写并显式绑定
TP6路由完全重构,取消自动解析、模糊匹配和Behavior机制,所有规则必须在app/route.php中显式注册:
- 原
Route::get('user/:id', 'index/user/read')→ 改为Route::get('user/:id', [\app\controller\User::class, 'read']) - 分组路由需用闭包包裹:
Route::group('api/v1', function () { Route::get('<module>/', 'api.v1.:module/index'); });</module> - 中间件不再通过
middleware.php全局附加 → 必须用Route::middleware()或控制器构造函数中$this->middleware()显式绑定 -
request()->module()、request()->controller()等方法全部失效 → 获取应用名用app('http')->getName(),获取参数用request()->param('id')
模型、跳转、Session等常用功能需补装或重写
TP6默认精简,很多TP5习以为常的功能需要单独安装或手动实现:
- 模板引擎默认不启用 → 执行
composer require topthink/think-view,并在config/view.php中开启'layout_on'=>true -
$this->success()、$this->error()、redirect()被移除 → 安装扩展composer require liliuwei/thinkphp-jump,并在基类中引入use \liliuwei\think\Jump; - Session默认未开启 → 在
app/middleware.php中加入\think\middleware\SessionInit::class - 模型关联删除:
$article->together('comments')(TP5)→ 改为$article->together(['comments'])(TP6传数组) - 字段排除:
field('id,content', true)→ 改为withoutField('id,content')
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











