一、环境准备与框架安装
在开始之前,确保你的系统已安装PHP(7.1+)、Composer和MySQL数据库。
1.1 使用Composer安装ThinkPHP
composer create-project topthink/think blog
cd blog
1.2 配置数据库连接
打开config/database.php文件,修改以下配置:
'hostname' => '127.0.0.1',
'database' => 'blog_db',
'username' => 'root',
'password' => 'your_password',
二、数据库设计与模型创建
2.1 创建文章表
使用ThinkPHP命令行工具生成数据库迁移文件:
php think make:migration CreatePostsTable
在生成的迁移文件中定义表结构:
<?php
use think\migration\Migration;
use think\migration\db\Column;
class CreatePostsTable extends Migration
{
public function change()
{
$table = $this->table('posts');
$table->addColumn('title', 'string', ['limit' => 255])
->addColumn('content', 'text')
->addColumn('user_id', 'integer')
->addColumn('created_at', 'timestamp', ['default' => 'CURRENT_TIMESTAMP'])
->addColumn('updated_at', 'timestamp', ['default' => 'CURRENT_TIMESTAMP'])
->create();
}
}
运行迁移:
php think migrate:run
2.2 创建文章模型
php think make:model Post
编辑app/model/Post.php:
<?php
namespace app\model;
use think\Model;
class Post extends Model
{
// 设置表名
protected $name = 'posts';
// 自动写入时间戳
protected $autoWriteTimestamp = true;
// 定义创建时间字段
protected $createTime = 'created_at';
// 定义更新时间字段
protected $updateTime = 'updated_at';
// 字段类型转换
protected $type = [
'user_id' => 'integer',
];
}
三、控制器与路由配置
3.1 创建博客控制器
php think make:controller Blog
编辑app/controller/Blog.php:
<?php
namespace app\controller;
use app\BaseController;
use app\model\Post;
use think\facade\View;
class Blog extends BaseController
{
// 显示所有文章
public function index()
{
$posts = Post::select();
return View::fetch('index', ['posts' => $posts]);
}
// 显示单篇文章
public function read($id)
{
$post = Post::find($id);
if (!$post) {
return $this->error('文章不存在');
}
return View::fetch('read', ['post' => $post]);
}
// 创建新文章
public function create()
{
return View::fetch('create');
}
// 保存文章
public function save()
{
$data = $this->request->post();
// 验证数据
$validate = new \app\validate\Post();
if (!$validate->check($data)) {
return $this->error($validate->getError());
}
$post = new Post();
$post->save($data);
return $this->success('文章发布成功', url('blog/read', ['id' => $post->id]));
}
}
3.2 配置路由
编辑route/app.php:
<?php
use think\facade\Route;
// 博客路由
Route::get('blog', 'Blog/index');
Route::get('blog/:id', 'Blog/read');
Route::get('blog/create', 'Blog/create');
Route::post('blog/save', 'Blog/save');
四、视图模板开发
4.1 文章列表页面
创建view/blog/index.html:
<!DOCTYPE html>
<html>
<head>
<title>我的博客</title>
</head>
<body>
<h1>文章列表</h1>
<a href="{:url('blog/create')}" rel="external nofollow" >写文章</a>
{volist name="posts" id="post"}
<div class="post">
<h2><a href="{:url('blog/read', ['id'=>$post.id])}" rel="external nofollow" >{$post.title}</a></h2>
<p>发布时间: {$post.created_at}</p>
</div>
{/volist}
</body>
</html>
4.2 文章详情页面
创建view/blog/read.html:
<!DOCTYPE html>
<html>
<head>
<title>{$post.title}</title>
</head>
<body>
<h1>{$post.title}</h1>
<p>发布时间: {$post.created_at}</p>
<div>{$post.content}</div>
<a href="{:url('blog/index')}" rel="external nofollow" >返回列表</a>
</body>
</html>
4.3 文章创建页面
创建view/blog/create.html:
<!DOCTYPE html>
<html>
<head>
<title>写文章</title>
</head>
<body>
<h1>写新文章</h1>
<form action="{:url('blog/save')}" method="post">
<div>
<label>标题</label>
<input type="text" name="title" required>
</div>
<div>
<label>内容</label>
<textarea name="content" rows="10" required></textarea>
</div>
<button type="submit">发布</button>
</form>
</body>
</html>
五、数据验证与安全处理
5.1 创建验证器
php think make:validate Post
编辑app/validate/Post.php:
<?php
namespace app\validate;
use think\Validate;
class Post extends Validate
{
protected $rule = [
'title' => 'require|min:5|max:255',
'content' => 'require|min:10',
];
protected $message = [
'title.require' => '标题不能为空',
'title.min' => '标题至少5个字符',
'title.max' => '标题最多255个字符',
'content.require' => '内容不能为空',
'content.min' => '内容至少10个字符',
];
}
5.2 防止XSS攻击
在Post模型中添加自动过滤:
<?php
namespace app\model;
use think\Model;
class Post extends Model
{
// 之前代码...
// 设置字段自动过滤
protected $filter = ['title', 'content'];
// 标题获取器 - 过滤HTML标签
public function getTitleAttr($value)
{
return htmlspecialchars($value);
}
// 内容获取器 - 允许一些安全标签
public function getContentAttr($value)
{
$config = HTMLPurifier_Config::createDefault();
$purifier = new HTMLPurifier($config);
return $purifier->purify($value);
}
}
六、功能扩展与优化
6.1 添加分页功能
修改Blog控制器的index方法:
public function index()
{
$page = $this->request->param('page', 1);
$limit = 10;
$posts = Post::paginate([
'list_rows' => $limit,
'page' => $page,
]);
return View::fetch('index', ['posts' => $posts]);
}
在视图模板中添加分页显示:
<div class="pagination">
{$posts|raw}
</div>
6.2 添加文章分类功能
创建分类表和模型,并在文章表中添加category_id字段。
// 在Post模型中添加关联
public function category()
{
return $this->belongsTo(Category::class);
}
七、部署与性能优化
7.1 开启路由缓存
php think optimize:route
7.2 配置缓存驱动
在config/cache.php中配置:
'default' => 'redis',
'stores' => [
'redis' => [
'type' => 'redis',
'host' => '127.0.0.1',
'port' => 6379,
'password' => '',
'select' => 0,
'timeout' => 0,
'prefix' => 'blog_',
],
],
7.3 使用OPcache加速
在php.ini中启用OPcache:
opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=10000
opcache.revalidate_freq=60
总结
通过本教程,我们使用ThinkPHP构建了一个功能完整的博客系统,涵盖了MVC架构的各个组成部分。这个示例展示了ThinkPHP的核心特性,包括:
- 数据库迁移和模型定义
- 控制器逻辑处理
- 视图模板渲染
- 数据验证和安全处理
- 性能优化技巧
ThinkPHP提供了丰富的功能和良好的文档,适合快速开发各种Web应用程序。你可以在此基础上继续扩展功能,如用户认证、评论系统、文章搜索等。