从零开始,全面掌握ThinkPHP 6.x框架在企业级项目中的实战应用
一、项目架构设计与环境配置
本教程将构建一个完整的电商后台管理系统,包含用户管理、商品管理、订单处理等核心模块。采用前后端分离架构,后端使用ThinkPHP 6.x提供RESTful API接口。
项目技术栈:
- 后端框架:ThinkPHP 6.1 + PHP 7.4+
- 数据库:MySQL 8.0 + Redis 6.0
- API文档:ThinkPHP-Swagger扩展
- 权限控制:JWT Token + RBAC权限模型
- 队列处理:Redis队列 + 定时任务
二、ThinkPHP 6.x项目初始化与配置
步骤1:项目创建与目录结构优化
# 创建ThinkPHP 6.x项目 composer create-project topthink/think tp6-shop-api # 优化目录结构 app/ ├── common/ # 公共模块 │ ├── lib/ # 公共类库 │ ├── service/ # 服务层 │ └── traits/ # 公共Trait ├── admin/ # 后台管理模块 ├── api/ # API接口模块 ├── middleware/ # 中间件目录 ├── provider/ # 服务提供者 └── exception/ # 异常处理 # 安装必要扩展 composer require topthink/think-migration composer require topthink/think-jwt composer require topthink/think-swagger
步骤2:数据库配置与迁移文件
// config/database.php 数据库配置
return [
'default' => 'mysql',
'connections' => [
'mysql' => [
'type' => 'mysql',
'hostname' => '127.0.0.1',
'database' => 'shop_db',
'username' => 'root',
'password' => '',
'hostport' => '3306',
'charset' => 'utf8mb4',
'prefix' => 'shop_',
'break_reconnect' => true,
'trigger_sql' => true,
]
]
];
// 创建用户表迁移文件
<?php
declare(strict_types=1);
use thinkmigrationMigrator;
class CreateUserTable extends Migrator
{
public function change()
{
$table = $this->table('user', [
'comment' => '用户表',
'engine' => 'InnoDB',
'charset' => 'utf8mb4'
]);
$table->addColumn('username', 'string', [
'limit' => 50,
'default' => '',
'comment' => '用户名'
])
->addColumn('email', 'string', [
'limit' => 100,
'default' => '',
'comment' => '邮箱'
])
->addColumn('password', 'string', [
'limit' => 255,
'default' => '',
'comment' => '密码'
])
->addColumn('status', 'integer', [
'limit' => 1,
'default' => 1,
'comment' => '状态:1正常 0禁用'
])
->addColumn('last_login_time', 'integer', [
'default' => 0,
'comment' => '最后登录时间'
])
->addColumn('create_time', 'integer')
->addColumn('update_time', 'integer')
->addIndex(['username'], ['unique' => true])
->addIndex(['email'], ['unique' => true])
->create();
}
}
三、JWT认证与权限控制系统实现
JWT认证中间件实现
// app/middleware/JwtAuth.php
<?php
declare(strict_types=1);
namespace appmiddleware;
use thinkfacadeConfig;
use FirebaseJWTJWT;
use FirebaseJWTKey;
class JwtAuth
{
public function handle($request, Closure $next)
{
// 排除不需要认证的路由
$except = ['api/auth/login', 'api/auth/register'];
if (in_array($request->pathinfo(), $except)) {
return $next($request);
}
$token = $request->header('Authorization');
if (!$token) {
return json(['code' => 401, 'msg' => 'Token不存在']);
}
try {
$token = str_replace('Bearer ', '', $token);
$config = Config::get('jwt');
$decoded = JWT::decode($token, new Key($config['key'], $config['alg']));
$request->user = $decoded->data;
} catch (Exception $e) {
return json(['code' => 401, 'msg' => 'Token无效或已过期']);
}
return $next($request);
}
}
// app/common/service/AuthService.php
<?php
declare(strict_types=1);
namespace appcommonservice;
use thinkfacadeConfig;
use FirebaseJWTJWT;
use appcommonmodelUser;
class AuthService
{
/**
* 生成JWT Token
*/
public static function generateToken($user): string
{
$config = Config::get('jwt');
$payload = [
'iss' => $config['iss'], // 签发者
'aud' => $config['aud'], // 接收方
'iat' => time(), // 签发时间
'exp' => time() + $config['exp'], // 过期时间
'data' => [
'user_id' => $user->id,
'username' => $user->username,
'role' => $user->role
]
];
return JWT::encode($payload, $config['key'], $config['alg']);
}
/**
* 用户登录验证
*/
public static function login($username, $password): array
{
$user = User::where('username', $username)
->where('status', 1)
->find();
if (!$user || !password_verify($password, $user->password)) {
throw new Exception('用户名或密码错误');
}
// 更新登录信息
$user->last_login_time = time();
$user->save();
// 生成Token
$token = self::generateToken($user);
return [
'token' => $token,
'user' => [
'id' => $user->id,
'username' => $user->username,
'email' => $user->email
]
];
}
}
四、RESTful API接口开发实战
商品管理API控制器
// app/api/controller/ProductController.php
<?php
declare(strict_types=1);
namespace appapicontroller;
use thinkfacadeRequest;
use thinkfacadeValidate;
use appcommonserviceProductService;
class ProductController extends BaseController
{
/**
* @OAGet(
* path="/api/products",
* tags={"商品管理"},
* summary="获取商品列表",
* security={{"bearerAuth":{}}}
* )
*/
public function index()
{
$params = Request::only([
'page' => 1,
'limit' => 15,
'category_id' => '',
'keyword' => '',
'status' => 1
]);
$result = ProductService::getList($params);
return $this->success('获取成功', $result);
}
/**
* @OAPost(
* path="/api/products",
* tags={"商品管理"},
* summary="创建商品",
* security={{"bearerAuth":{}}}
* )
*/
public function save()
{
$data = Request::post();
// 数据验证
$validate = Validate::rule([
'name|商品名称' => 'require|max:100',
'category_id|分类' => 'require|number',
'price|价格' => 'require|float',
'stock|库存' => 'require|number|min:0'
]);
if (!$validate->check($data)) {
return $this->error($validate->getError());
}
// 处理上传图片
if (Request::file('image')) {
$file = Request::file('image');
$saveName = thinkfacadeFilesystem::putFile('products', $file);
$data['image'] = $saveName;
}
$product = ProductService::create($data);
// 记录操作日志
$this->log('创建商品', $product->id);
return $this->success('创建成功', $product);
}
/**
* @OAPut(
* path="/api/products/{id}",
* tags={"商品管理"},
* summary="更新商品",
* security={{"bearerAuth":{}}}
* )
*/
public function update($id)
{
$data = Request::put();
$product = ProductService::update($id, $data);
// 清除商品缓存
cache('product_' . $id, null);
$this->log('更新商品', $id);
return $this->success('更新成功', $product);
}
/**
* 商品搜索(支持ES)
*/
public function search()
{
$keyword = Request::param('keyword');
$page = Request::param('page', 1);
// 使用Elasticsearch进行全文搜索
if (class_exists('ElasticsearchClient')) {
$result = ProductService::elasticSearch($keyword, $page);
} else {
// 降级到数据库搜索
$result = ProductService::databaseSearch($keyword, $page);
}
return $this->success('搜索成功', $result);
}
}
五、服务层与数据模型设计
商品服务层实现
// app/common/service/ProductService.php
<?php
declare(strict_types=1);
namespace appcommonservice;
use thinkfacadeCache;
use thinkfacadeDb;
use appcommonmodelProduct;
use appcommonexceptionBusinessException;
class ProductService
{
/**
* 获取商品列表(带缓存)
*/
public static function getList(array $params): array
{
$cacheKey = 'product_list_' . md5(json_encode($params));
// 尝试从缓存获取
if ($data = Cache::get($cacheKey)) {
return $data;
}
$query = Product::with(['category', 'sku'])
->where('status', $params['status']);
// 分类筛选
if (!empty($params['category_id'])) {
$query->where('category_id', $params['category_id']);
}
// 关键词搜索
if (!empty($params['keyword'])) {
$query->whereLike('name|description', '%' . $params['keyword'] . '%');
}
// 排序
$query->order('sort', 'desc')
->order('create_time', 'desc');
// 分页
$total = $query->count();
$list = $query->page($params['page'], $params['limit'])
->select()
->toArray();
$result = [
'list' => $list,
'total' => $total,
'page' => $params['page'],
'limit' => $params['limit']
];
// 缓存5分钟
Cache::set($cacheKey, $result, 300);
return $result;
}
/**
* 创建商品(事务处理)
*/
public static function create(array $data): Product
{
Db::startTrans();
try {
$product = new Product();
$product->save($data);
// 创建商品SKU
if (!empty($data['sku_list'])) {
foreach ($data['sku_list'] as $sku) {
$product->sku()->save($sku);
}
}
// 记录商品创建日志
event('ProductCreated', $product);
Db::commit();
return $product;
} catch (Exception $e) {
Db::rollback();
throw new BusinessException('商品创建失败:' . $e->getMessage());
}
}
/**
* 商品库存检查与扣减
*/
public static function checkAndReduceStock($productId, $skuId, $quantity): bool
{
$lockKey = 'product_stock_lock_' . $productId . '_' . $skuId;
// 使用Redis分布式锁
$lock = Cache::store('redis')->lock($lockKey, 10);
if ($lock->acquire()) {
try {
if ($skuId) {
// SKU库存扣减
$sku = ProductSku::where('id', $skuId)
->where('product_id', $productId)
->lock(true)
->find();
if (!$sku || $sku->stock stock -= $quantity;
$sku->save();
} else {
// 商品总库存扣减
$product = Product::where('id', $productId)
->lock(true)
->find();
if (!$product || $product->stock stock -= $quantity;
$product->save();
}
return true;
} finally {
$lock->release();
}
}
throw new BusinessException('系统繁忙,请稍后重试');
}
}
六、性能优化与安全防护
安全防护措施:
- SQL注入防护:使用参数绑定和查询构造器
- XSS攻击防护:输出时使用htmlspecialchars过滤
- CSRF防护:启用CSRF中间件验证
- 暴力破解防护:登录失败次数限制
- 文件上传安全:文件类型、大小限制,重命名存储
性能优化方案:
- OPCache启用:PHP字节码缓存提升执行效率
- Redis缓存:热点数据缓存,减少数据库压力
- 数据库优化:合理索引,查询优化,读写分离
- 队列异步处理:耗时操作放入队列异步执行
- CDN加速:静态资源使用CDN分发
- API限流:防止恶意请求,保护系统资源
项目部署与扩展建议
建议部署环境:Nginx + PHP-FPM + MySQL + Redis。扩展方向:1)集成Elasticsearch实现商品搜索 2)添加WebSocket实现实时通知 3)集成支付接口 4)实现微服务架构拆分 5)添加API网关统一管理。
ThinkPHP 6.x
API开发
后台管理系统
企业级应用
API开发
后台管理系统
企业级应用

