在现代Web开发中,API接口开发已成为不可或缺的技能。本文将深入讲解如何使用ThinkPHP 6.x框架开发一套完整的RESTful风格的API接口,实现用户管理系统的核心功能。
一、RESTful API设计原则
在开始编码之前,我们需要了解RESTful API的基本设计原则:
- 使用HTTP方法表达操作类型(GET、POST、PUT、DELETE)
- URL代表资源,使用名词而非动词
- 返回统一格式的数据(通常为JSON)
- 无状态通信
二、项目初始化与配置
2.1 创建项目与数据库配置
使用Composer创建ThinkPHP项目:
composer create-project topthink/think api-project
cd api-project
配置数据库连接(config/database.php):
return [
'default' => 'mysql',
'connections' => [
'mysql' => [
'type' => 'mysql',
'hostname' => '127.0.0.1',
'database' => 'api_demo',
'username' => 'root',
'password' => '',
'charset' => 'utf8mb4',
'prefix' => 'api_',
],
],
];
2.2 创建数据库表
创建用户表:
CREATE TABLE `api_users` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL COMMENT '用户名',
`email` varchar(100) NOT NULL COMMENT '邮箱',
`password` varchar(255) NOT NULL COMMENT '密码',
`avatar` varchar(255) DEFAULT NULL COMMENT '头像',
`status` tinyint(1) DEFAULT '1' COMMENT '状态:0禁用,1启用',
`create_time` int(11) DEFAULT NULL COMMENT '创建时间',
`update_time` int(11) DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
三、核心功能实现
3.1 创建用户模型
创建app/model/User.php:
namespace appmodel;
use thinkModel;
use thinkmodelconcernSoftDelete;
class User extends Model
{
// 使用软删除
use SoftDelete;
protected $name = 'users';
protected $autoWriteTimestamp = true;
protected $deleteTime = 'delete_time';
protected $hidden = ['password', 'delete_time'];
// 自动加密密码
public function setPasswordAttr($value)
{
return password_hash($value, PASSWORD_DEFAULT);
}
// 状态获取器
public function getStatusAttr($value)
{
$status = [0 => '禁用', 1 => '启用'];
return $status[$value];
}
// 创建时间获取器
public function getCreateTimeAttr($value)
{
return date('Y-m-d H:i:s', $value);
}
}
3.2 实现JWT身份验证
安装JWT扩展:
composer require firebase/php-jwt
创建app/common/JwtAuth.php:
namespace appcommon;
use thinkfacadeRequest;
use FirebaseJWTJWT;
use FirebaseJWTKey;
use thinkfacadeConfig;
class JwtAuth
{
private static $key = 'your-secret-key'; // 加密密钥
// 生成token
public static function createToken($userId, $username)
{
$payload = [
'iss' => 'your-domain.com', // 签发者
'aud' => 'your-domain.com', // 接收方
'iat' => time(), // 签发时间
'nbf' => time(), // 生效时间
'exp' => time() + 7200, // 过期时间(2小时)
'data' => [
'user_id' => $userId,
'username' => $username
]
];
return JWT::encode($payload, self::$key, 'HS256');
}
// 验证token
public static function verifyToken($token)
{
try {
$decoded = JWT::decode($token, new Key(self::$key, 'HS256'));
return (array) $decoded->data;
} catch (Exception $e) {
return false;
}
}
// 获取当前用户ID
public static function getCurrentUserId()
{
$token = Request::header('Authorization');
if (!$token) {
return false;
}
// 去除Bearer前缀
if (strpos($token, 'Bearer ') === 0) {
$token = substr($token, 7);
}
$userData = self::verifyToken($token);
return $userData ? $userData['user_id'] : false;
}
}
3.3 创建中间件进行权限验证
创建app/middleware/JwtAuth.php:
namespace appmiddleware;
use appcommonJwtAuth;
use thinkfacadeRequest;
use thinkResponse;
class JwtAuthMiddleware
{
public function handle($request, Closure $next)
{
// 排除登录和注册接口
$excludeRoutes = ['user/login', 'user/register'];
$path = $request->pathinfo();
if (in_array($path, $excludeRoutes)) {
return $next($request);
}
$token = Request::header('Authorization');
if (!$token) {
return json(['code' => 401, 'msg' => 'Token不能为空'], 401);
}
// 去除Bearer前缀
if (strpos($token, 'Bearer ') === 0) {
$token = substr($token, 7);
}
$userData = JwtAuth::verifyToken($token);
if (!$userData) {
return json(['code' => 401, 'msg' => 'Token无效或已过期'], 401);
}
// 将用户信息添加到请求对象中
$request->user = $userData;
return $next($request);
}
}
注册中间件(app/middleware.php):
return [
// 全局中间件
appmiddlewareJwtAuthMiddleware::class,
];
3.4 创建用户控制器
创建app/controller/User.php:
namespace appcontroller;
use appBaseController;
use appmodelUser as UserModel;
use appcommonJwtAuth;
use thinkfacadeRequest;
use thinkfacadeValidate;
class User extends BaseController
{
// 用户注册
public function register()
{
$data = Request::only(['username', 'email', 'password']);
// 数据验证
$validate = Validate::rule([
'username|用户名' => 'require|alphaNum|length:3,20|unique:users',
'email|邮箱' => 'require|email|unique:users',
'password|密码' => 'require|length:6,20',
]);
if (!$validate->check($data)) {
return json(['code' => 400, 'msg' => $validate->getError()], 400);
}
// 创建用户
$user = UserModel::create($data);
if ($user) {
return json([
'code' => 200,
'msg' => '注册成功',
'data' => [
'user_id' => $user->id,
'username' => $user->username,
'email' => $user->email
]
]);
} else {
return json(['code' => 500, 'msg' => '注册失败'], 500);
}
}
// 用户登录
public function login()
{
$data = Request::only(['username', 'password']);
// 数据验证
$validate = Validate::rule([
'username|用户名' => 'require',
'password|密码' => 'require',
]);
if (!$validate->check($data)) {
return json(['code' => 400, 'msg' => $validate->getError()], 400);
}
// 查找用户
$user = UserModel::where('username', $data['username'])
->whereOr('email', $data['username'])
->find();
if (!$user || !password_verify($data['password'], $user->password)) {
return json(['code' => 401, 'msg' => '用户名或密码错误'], 401);
}
if ($user->status == 0) {
return json(['code' => 401, 'msg' => '账号已被禁用'], 401);
}
// 生成token
$token = JwtAuth::createToken($user->id, $user->username);
return json([
'code' => 200,
'msg' => '登录成功',
'data' => [
'token' => $token,
'user_info' => [
'user_id' => $user->id,
'username' => $user->username,
'email' => $user->email,
'avatar' => $user->avatar
]
]
]);
}
// 获取用户信息
public function info()
{
$userId = JwtAuth::getCurrentUserId();
$user = UserModel::find($userId);
if (!$user) {
return json(['code' => 404, 'msg' => '用户不存在'], 404);
}
return json([
'code' => 200,
'msg' => '获取成功',
'data' => $user
]);
}
// 更新用户信息
public function update()
{
$userId = JwtAuth::getCurrentUserId();
$data = Request::only(['email', 'avatar']);
// 数据验证
$validate = Validate::rule([
'email|邮箱' => 'email|unique:users,email,' . $userId,
'avatar|头像' => 'url',
]);
if (!$validate->check($data)) {
return json(['code' => 400, 'msg' => $validate->getError()], 400);
}
// 更新用户信息
$user = UserModel::find($userId);
$result = $user->save($data);
if ($result) {
return json([
'code' => 200,
'msg' => '更新成功',
'data' => $user
]);
} else {
return json(['code' => 500, 'msg' => '更新失败'], 500);
}
}
// 删除用户(软删除)
public function delete()
{
$userId = JwtAuth::getCurrentUserId();
$user = UserModel::find($userId);
if (!$user) {
return json(['code' => 404, 'msg' => '用户不存在'], 404);
}
$result = $user->delete();
if ($result) {
return json(['code' => 200, 'msg' => '删除成功']);
} else {
return json(['code' => 500, 'msg' => '删除失败'], 500);
}
}
}
3.5 配置API路由
创建route/api.php:
use thinkfacadeRoute;
// 用户路由组
Route::group('user', function() {
Route::post('register', 'user/register'); // 用户注册
Route::post('login', 'user/login'); // 用户登录
Route::get('info', 'user/info'); // 获取用户信息
Route::put('update', 'user/update'); // 更新用户信息
Route::delete('delete', 'user/delete'); // 删除用户
});
四、统一响应处理
4.1 创建基础控制器
修改app/BaseController.php,添加统一响应方法:
namespace app;
use thinkApp;
use thinkexceptionValidateException;
use thinkValidate;
abstract class BaseController
{
protected $app;
protected $request;
public function __construct(App $app)
{
$this->app = $app;
$this->request = $this->app->request;
}
// 成功响应
protected function success($data = null, $msg = '操作成功', $code = 200)
{
$result = [
'code' => $code,
'msg' => $msg,
'data' => $data
];
return json($result);
}
// 错误响应
protected function error($msg = '操作失败', $code = 500, $data = null)
{
$result = [
'code' => $code,
'msg' => $msg,
'data' => $data
];
return json($result, $code);
}
// 验证数据
protected function validateData($data, $validate, $message = [])
{
try {
validate($validate, $message)->check($data);
} catch (ValidateException $e) {
return $this->error($e->getMessage(), 400);
}
return true;
}
}
4.2 全局异常处理
修改app/ExceptionHandle.php,处理API异常:
public function render($request, Throwable $e): Response
{
// 如果是API请求
if ($request->isAjax() || strpos($request->pathinfo(), 'api/') === 0) {
// 记录异常日志
Log::error($e->getMessage());
// 返回JSON格式的错误信息
$code = $e->getCode() ?: 500;
$msg = $e->getMessage();
// 生产环境隐藏详细错误
if (!env('app_debug') && $code == 500) {
$msg = '内部服务器错误';
}
return json([
'code' => $code,
'msg' => $msg,
'data' => null
], $code);
}
// 其他请求使用默认异常处理
return parent::render($request, $e);
}
五、API文档生成与测试
5.1 使用Swagger生成API文档
安装swagger-php:
composer require zircote/swagger-php
在控制器中添加注解:
/**
* @OAInfo(title="用户管理API", version="1.0.0")
*/
class User extends BaseController
{
/**
* 用户注册
* @OAPost(
* path="/user/register",
* summary="用户注册",
* tags={"用户"},
* @OARequestBody(
* required=true,
* @OAJsonContent(
* required={"username", "email", "password"},
* @OAProperty(property="username", type="string", example="testuser"),
* @OAProperty(property="email", type="string", format="email", example="test@example.com"),
* @OAProperty(property="password", type="string", format="password", example="123456")
* )
* ),
* @OAResponse(
* response=200,
* description="注册成功",
* @OAJsonContent(ref="#/components/schemas/ApiResponse")
* )
* )
*/
public function register()
{
// 方法实现
}
}
5.2 使用Postman测试API
创建Postman集合,包含以下请求:
- POST /user/register – 用户注册
- POST /user/login – 用户登录
- GET /user/info – 获取用户信息(需要Authorization头)
- PUT /user/update – 更新用户信息(需要Authorization头)
- DELETE /user/delete – 删除用户(需要Authorization头)
六、部署与性能优化
6.1 生产环境配置
修改.env文件:
APP_DEBUG = false
APP_TRACE = false
// 数据库配置
DATABASE_HOSTNAME = 127.0.0.1
DATABASE_DATABASE = api_demo
DATABASE_USERNAME = root
DATABASE_PASSWORD = your_password
6.2 使用Redis缓存
安装predis扩展:
composer require predis/predis
配置Redis(config/cache.php):
return [
'default' => 'redis',
'stores' => [
'redis' => [
'type' => 'redis',
'host' => '127.0.0.1',
'port' => 6379,
'password' => '',
'select' => 0,
'timeout' => 0,
'persistent' => false,
],
],
];
在控制器中使用缓存:
use thinkfacadeCache;
// 获取用户信息时使用缓存
public function info()
{
$userId = JwtAuth::getCurrentUserId();
$cacheKey = 'user_info_' . $userId;
$user = Cache::remember($cacheKey, function() use ($userId) {
return UserModel::find($userId);
}, 3600); // 缓存1小时
if (!$user) {
return $this->error('用户不存在', 404);
}
return $this->success($user, '获取成功');
}
七、总结
本文详细介绍了如何使用ThinkPHP 6.x开发一套完整的RESTful API接口,涵盖了用户管理系统的核心功能。通过本教程,你学会了:
- ThinkPHP项目初始化与配置
- RESTful API设计原则与实现
- JWT身份验证的实现
- 中间件的使用与自定义
- 统一响应格式与异常处理
- API文档生成与测试
- 性能优化与生产环境部署
这套API系统遵循了RESTful设计原则,具有良好的可扩展性和维护性。你可以在此基础上继续扩展更多功能,如权限管理、文件上传、消息队列等,构建更复杂的应用系统。
ThinkPHP 6.x提供了强大的功能和灵活的扩展机制,非常适合API接口开发。希望本教程能帮助你在ThinkPHP API开发领域取得进步!

