要用ThinkPHP 8.0搭建可运行的轻量级CMS,需确保PHP 8.0+环境,正确配置四类核心路由(域名隔离、栏目页、文章页、静态兜底),建立Category与Article模型及belongsTo关联,实现模板自动匹配(推荐View驱动或中间件),并生成/public/news/{id}.html静态页。

想用 ThinkPHP 8.0 搭建一个能真正跑起来的轻量级 CMS 练手,不是只写个首页或模拟后台,而是要让栏目能嵌套、文章能按分类自动匹配模板、URL 能带 .html 后缀且不 404、静态页生成后还能被动态路由兜底——这些卡点不手动填平,项目连首页都加载不全。
初始化项目并确认 PHP 环境
打开命令行,先执行 php -v,必须看到 PHP 8.0+(如 8.2.15),低于此版本 composer 会静默降级安装 ThinkPHP 6,后续所有路由和模型功能都将失效。
若版本不符,不要继续下一步。去 phpEnv 或 XAMPP 控制面板里切换 PHP 版本,再手动把新 PHP 路径(如 D:\phpEnv\php\php-8.2)加到系统环境变量 Path 最前面,删掉旧路径,重启终端。
运行:composer create-project topthink/think tp-cms --no-interaction
立即学习“PHP免费学习笔记(深入)”;
进到 tp-cms 目录,检查 vendor/autoload.php 是否真实存在——缺失则执行 composer install 补全依赖,别删项目重装。
配置 CMS 必需的四类核心路由
打开 config/route.php,删除默认的 Route::get('/', ...) 和 Route::get('/hello', ...),全部替换成以下结构:
① 前台域名隔离:Route::domain('www', ['middleware' => []]);
② 栏目页规则(带正则防路径遍历):Route::rule('category/
③ 文章页通配规则:Route::rule('article/
④ 静态化兜底(无后缀也能跳):Route::rule('news/
注意:别用 Route::rule('article/:id', ...) 这种裸参数写法,TP8 不再隐式推导控制器,不写完整命名空间会直接 404。
建立栏目与文章模型及关联
执行命令:php think make:model model/Category
在 app/model/Category.php 中补全:use think\Model; class Category extends Model { protected $table = 'cms_category'; }
同理创建文章模型:php think make:model model/Article
在 Article.php 中添加关联方法:public function category() { return $this->belongsTo(Category::class, 'category_id', 'id'); }
这一步漏写 belongsTo,模板里调用 {$article->category->name} 就会报错,N+1 查询问题也会立刻暴露。
实现模板自动匹配逻辑
方法一:重写 View 驱动(推荐)
在 app/common.php 末尾追加:view()->config(['view_path' => app()->getAppPath() . 'view/']);
然后在 app/middleware/ViewMatch.php 中写匹配逻辑:根据请求 URL 解析出 category/news → 自动加载 view/category_news.html。
方法二:中间件拦截(更可控)
新建 app/middleware/TemplateResolver.php,在 handle 方法中解析 request->url(),提取二级路径,拼接为 $template = 'category_' . $path[1];
再调用 View::fetch($template),避免硬编码模板名。
方法三:控制器内手动指定(仅限调试)
在 index/controller/Category.php 的 index 方法末尾加:return View::fetch('category_' . $name);
但上线前必须切回前两种方式,否则每新增一个栏目都要改控制器。
生成静态 HTML 页面
创建命令行指令:php think make:command BuildStatic
在 app/command/BuildStatic.php 的 execute 方法中,查询所有已发布文章:$articles = Article::where('status', 1)->select();
对每篇文章执行:file_put_contents(public_path() . '/news/' . $article->id . '.html', View::fetch('article_detail', ['article' => $article]));
最后运行:php think build:static,生成的 HTML 文件必须落在 public/news/ 目录下,否则 Nginx/Apache 无法直接响应。



















