Skip to content

ThinkPHP8 后端API开发规范

本文档定义后端API开发的标准流程、代码规范和最佳实践


一、响应格式标准

1.1 状态码常量

定义位置:api/app/common.php

php
SUCCESS = 0              // 操作成功
ERROR_SYSTEM = 1000      // 系统错误
ERROR_PARAMS = 1001      // 参数错误
ERROR_SQL = 1002         // 数据库操作错误
ERROR_PATH = 1003        // 路径错误
ERROR_ACCESS = 1004      // 无权限
ERROR_LOGIC = 2000       // 逻辑错误(提示性)
ERROR_TOKEN = 2001       // token失效
ERROR_PARAMS_CHECK = 2002 // 参数验证失败
ERROR_SECURITY = 3000    // 安全验证

1.2 统一响应结构

json
{
  "responseHeader": {
    "timestamp": 1234567890,
    "returnCode": 0,
    "message": "操作成功"
  },
  "responseData": {
    // 业务数据
  }
}

二、控制器规范

2.1 基本结构

php
namespace app\common\controller;

use app\BaseController as AppBaseController;
use app\common\model\XxxModel;
use app\common\validate\XxxValidate;
use think\facade\Request;

class XxxController extends AppBaseController
{
    /**
     * 获取列表
     */
    public function getList()
    {
        // 1. 参数验证
        $validate = new XxxValidate();
        if (!$validate->scene('list')->check(Request::param())) {
            return $this->sendResponse(ERROR_PARAMS, null, $validate->getError());
        }
        
        // 2. 业务逻辑
        $data = XxxModel::getList();
        
        // 3. 返回响应
        return $this->sendResponse(SUCCESS, $data);
    }
}

2.2 核心方法

  • $this->sendResponse($code, $data, $message) - 返回JSON响应
  • Request::param('key') - 获取参数
  • saas_abort(ERROR_CODE, null, '消息') - 抛出异常

三、模型规范

3.1 文件位置与命名

  • 路径:app/common/model/XxxModel.php
  • 命名:PascalCase驼峰命名

3.2 模型定义

php
namespace app\common\model;

use think\Model;

class XxxModel extends Model
{
    // 表名(无前缀,系统自动加 sets_)
    protected $name = 'table_name';
    
    // 主键
    protected $pk = 'id';
    
    // 时间戳
    protected $autoWriteTimestamp = false;
    
    // JSON字段自动序列化
    protected $json = ['field1', 'field2'];
    
    // 字段类型转换
    protected $type = [
        'total' => 'integer',
        'created_at' => 'integer'
    ];
    
    // 静态业务方法
    public static function createXxx($data)
    {
        $model = new self();
        $model->field = $data['field'];
        $model->save();
        return $model->id;
    }
    
    // 查询方法
    public static function findByXxx($value)
    {
        return self::where('field', $value)->find();
    }
}

3.3 数据库表前缀

  • 所有表自动加前缀 sets_
  • 模型中只需定义表名:protected $name = 'mj_generation_batch'
  • 实际表名:sets_mj_generation_batch

四、验证器规范

4.1 文件位置

路径:app/common/validate/XxxValidate.php

4.2 验证器定义

php
namespace app\common\validate;

use think\Validate;

class XxxValidate extends Validate
{
    protected $rule = [
        'batch_id' => 'require|alphaNum|length:10,50',
        'page' => 'number|egt:1',
        'limit' => 'number|between:1,100'
    ];
    
    protected $message = [
        'batch_id.require' => '批次ID不能为空',
        'page.egt' => '页码必须大于等于1'
    ];
    
    protected $scene = [
        'list' => ['page', 'limit'],
        'detail' => ['batch_id'],
        'delete' => ['batch_id']
    ];
}

4.3 使用方式

php
$validate = new XxxValidate();
if (!$validate->scene('list')->check(Request::param())) {
    return $this->sendResponse(ERROR_PARAMS, null, $validate->getError());
}

五、路由规范

5.1 RESTful风格

定义位置:api/route/app.php

php
// 批次管理
Route::get('common/midjourney/batch/list', 'common.MidjourneyTool/getBatchList');
Route::get('common/midjourney/batch/detail', 'common.MidjourneyTool/getBatchDetail');
Route::post('common/midjourney/batch/delete', 'common.MidjourneyTool/deleteBatch');

// Hook推荐接口(标准模块访问方式)
Route::post('common/midjourney/hook/recommendation', 'common.HookRecommendation/getRecommendation');
Route::post('common/midjourney/hook/batch-recommendation', 'common.HookRecommendation/batchRecommendation');
Route::get('common/midjourney/hook/health', function () {
    return json([
        'code' => 200,
        'msg' => 'Hook推荐服务正常',
        'data' => [
            'service' => 'HookRecommendation',
            'status' => 'running',
            'timestamp' => time()
        ]
    ]);
});

// Hook推荐接口(快捷别名访问方式)
Route::group('api', function () {
    Route::post('hook/recommendation', 'common/HookRecommendation/getRecommendation');
    Route::post('hook/batch-recommendation', 'common/HookRecommendation/batchRecommendation');
    Route::get('hook/health', function () {
        return json([
            'code' => 200,
            'msg' => 'Hook推荐服务正常',
            'data' => [
                'service' => 'HookRecommendation',
                'status' => 'running',
                'timestamp' => time()
            ]
        ]);
    });
});

5.2 访问路径规范

  • 标准模块访问http://localhost:8000/common/midjourney/hook/{endpoint}
  • 快捷别名访问http://localhost:8000/api/hook/{endpoint}
  • 优先使用标准模块访问方式(经过验证稳定可靠)

5.3 命名规范

  • 小写 + 斜杠分隔
  • 资源名称使用复数(如 batches)或单数+动词(如 batch/list
  • Hook相关接口统一使用hook前缀

六、命名约定

类型规范示例
控制器PascalCase + ControllerMidjourneyToolController
模型PascalCaseMjGenerationBatch
验证器PascalCase + ValidateMjGenerationBatchValidate
方法camelCasegetBatchList, createBatch
数据库表snake_casemj_generation_batch
常量UPPER_SNAKE_CASEERROR_PARAMS

七、API调用约束

7.1 curl命令规范

所有本地API调用必须遵循以下约束:

bash
# 标准curl调用格式(必须包含)
curl -s \
  --max-time 30 \
  --retry 3 \
  --retry-delay 2 \
  "http://localhost:8000/common/midjourney/endpoint"

# 或使用快捷别名方式
curl -s \
  --max-time 30 \
  --retry 3 \
  --retry-delay 2 \
  "http://localhost:8000/api/endpoint"

必须参数

  • --max-time 30:设置30秒超时时间
  • --retry 3:最多重试3次
  • --retry-delay 2:重试间隔2秒
  • -s:静默模式,减少输出干扰

7.2 测试脚本规范

创建测试脚本时必须包含:

bash
#!/bin/bash
# API测试脚本模板

# curl配置参数
TIMEOUT=30           # 超时时间30秒
MAX_RETRIES=3        # 最大重试次数
RETRY_DELAY=2        # 重试间隔2秒

# 标准化curl函数
curl_with_retry() {
    local url="$1"
    local method="${2:-GET}"
    local data="${3:-''}"
    
    if [[ "$method" == "POST" && -n "$data" ]]; then
        curl -s \
            --max-time $TIMEOUT \
            --retry $MAX_RETRIES \
            --retry-delay $RETRY_DELAY \
            -X "$method" \
            -H "Content-Type: application/json" \
            -d "$data" \
            "$url"
    else
        curl -s \
            --max-time $TIMEOUT \
            --retry $MAX_RETRIES \
            --retry-delay $RETRY_DELAY \
            "$url"
    fi
}

八、最佳实践

8.1 MVC分层

  • Controller - 参数验证、调用Model、返回响应
  • Model - 数据库操作、业务逻辑封装
  • Validate - 参数验证规则

8.2 示例参考

  • 模型:app/common/model/MjGenerationBatch.php
  • 验证器:app/common/validate/MjGenerationBatch.php
  • 控制器:app/common/controller/MidjourneyTool.php

文档维护: 修改本文档后,建议同步更新AI Memory以保持一致性