ThinkPHP5框架学习笔记
ThinkPHP是国内使用最广泛的PHP框架之一,以其简洁的语法、丰富的功能和完善的文档深受开发者喜爱。ThinkPHP5是框架的一次重大升级,全面拥抱了PHP7的新特性,引入了更多现代化设计。本文将系统地介绍ThinkPHP5的核心概念和实战技巧。
一、MVC架构详解
ThinkPHP遵循MVC(Model-View-Controller)设计模式,将应用分为三层:
// 控制器 - 处理请求和响应
namespace appindexcontroller;
class User extends Base
{
public function list()
{
$users = UserModel::where("status", 1)
->field("id,name,email")
->order("id", "desc")
->paginate(15);
$this->assign("users", $users);
return $this->fetch();
}
public function add()
{
if ($this->request->isPost()) {
$data = $this->request->post();
// 数据验证
$result = $this->validate($data, "User.add");
if (true !== $result) {
$this->error($result);
}
UserModel::create($data);
$this->success("添加成功", "list");
}
return $this->fetch();
}
}
二、数据库操作
ThinkPHP5提供了强大的数据库操作类,支持链式调用:
// 基本查询
$user = Db::name("user")->where("id", 1)->find();
$users = Db::name("user")->where("status", 1)->select();
// 链式操作
$list = Db::name("article")
->alias("a")
->join("category c", "a.category_id = c.id")
->where("a.status", 1)
->field("a.id,a.title,c.name as category")
->order("a.id", "desc")
->limit(10)
->select();
// 聚合查询
$count = Db::name("user")->count();
$maxAge = Db::name("user")->max("age");
// 事务操作
Db::startTrans();
try {
Db::name("order")->insert($orderData);
Db::name("stock")->where("id", $goodsId)->setDec("count", 1);
Db::commit();
} catch (Exception $e) {
Db::rollback();
}
三、模型与ORM
// 定义模型
namespace appindexmodel;
class Article extends Model
{
// 自动写入时间戳
protected $autoWriteTimestamp = true;
// 类型转换
protected $type = [
"publish_time" => "datetime",
];
// 获取器
public function getStatusTextAttr($value, $data)
{
$status = [0 => "草稿", 1 => "已发布"];
return $status[$data["status"]] ?? "未知";
}
// 关联定义
public function category()
{
return $this->belongsTo("Category", "category_id");
}
public function comments()
{
return $this->hasMany("Comment");
}
}
// 使用模型
$article = Article::with(["category", "comments"])->find(1);
echo $article->category->name;
echo $article->status_text; // 通过获取器
四、路由系统
// 路由配置 - application/route.php
use thinkRoute;
// 注册路由规则
Route::rule("hello/:name", "index/hello");
Route::get("users", "index/user/list");
Route::post("users", "index/user/add");
Route::put("users/:id", "index/user/update");
Route::delete("users/:id", "index/user/delete");
// 路由分组
Route::group("api", function () {
Route::get("users", "api/user/list");
Route::post("users", "api/user/create");
Route::resource("articles", "api/article");
})->middleware(["Auth", "Throttle"])->prefix("api/");
// RESTful路由
Route::resource("blog", "index/blog");
五、模板引擎
{extend name="layout/base" /}
{block name="title"}文章列表{/block}
{block name="content"}
{volist name="list" id="article"}
{$article.title}
{$article.content|mb_substr=0,200}
{$article.createtime|date="Y-m-d"}
{/volist}
{$list|raw}
{if condition="$article.status == 1"}
已发布
{else /}
草稿
{/if}
{/block}
六、中间件
// 定义中间件
namespace apphttpmiddleware;
class Cors
{
public function handle($request, Closure $next)
{
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET,POST,PUT,DELETE");
if ($request->method() == "OPTIONS") {
return response("", 204);
}
return $next($request);
}
}
// 注册中间件
// application/http.php
"middleware" => [
Cors::class,
],
七、命令行工具
// 自定义命令
namespace appcommand;
use thinkconsoleCommand;
use thinkconsoleInput;
use thinkconsoleOutput;
class SyncData extends Command
{
protected function configure()
{
$this->setName("sync:data")->setDescription("同步数据");
}
protected function execute(Input $input, Output $output)
{
$output->writeln("开始同步数据...");
// 同步逻辑
$output->writeln("同步完成!");
}
}
// 运行命令
php think sync:data
ThinkPHP5是一个功能完善、文档丰富的PHP框架。它的学习曲线相对平缓,适合从PHP原生开发过渡到框架开发的开发者。建议在学习过程中结合官方文档和实际项目练习,逐步掌握框架的各个组件。同时关注ThinkPHP6/8的新特性,它们在性能和开发体验上都有显著提升。