# OpenAPI接口开发模板

# 📁 目录结构

app/openapi/
├── app.xml                    # 应用配置文件
├── services.xml               # 服务配置
├── desktop.xml                # 桌面配置
├── controller/                # 控制器
│   └── admin/
│       ├── test.php          # 接口测试
│       ├── setting.php       # 接口设置
│       └── export.php        # 数据导出
├── lib/                       # 核心库文件
│   ├── conf.php              # 接口配置
│   ├── entrance.php          # 入口文件
│   ├── object.php            # 对象处理
│   ├── response.php          # 响应处理
│   ├── errorcode.php         # 错误码
│   ├── privilege.php         # 权限控制
│   ├── statistics.php        # 统计功能
│   └── api/                  # API实现
│       ├── params/           # 参数定义
│       │   ├── abstract.php  # 参数抽象类
│       │   ├── interface.php # 参数接口
│       │   ├── v1/           # v1版本参数
│       │   └── v2/           # v2版本参数
│       └── function/         # 功能实现
│           ├── abstract.php  # 功能抽象类
│           ├── interface.php # 功能接口
│           ├── v1/           # v1版本功能
│           └── v2/           # v2版本功能
├── model/                     # 数据模型
├── dbschema/                  # 数据库结构
├── testcase/                  # 测试用例
└── view/                      # 视图文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

# 🔧 核心文件模板

# 1. 应用配置 (app.xml)

<app>
    <name>接口模块名称</name>
    <description>接口模块描述</description>
    <author>
        <name>开发团队</name>
        <email>dev@example.com</email>
        <url>http://www.example.com</url>
    </author>
    <version>1.0</version>
    <license>license</license>
    <depends>
        <app>ome</app>
        <app>base</app>
    </depends>
</app>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 2. 接口配置 (lib/conf.php)

<?php
class openapi_conf
{
    public static function getMethods()
    {
        return array(
            'orders' => array(
                'label' => '订单',
                'methods' => array(
                    'getList' => '订单列表',
                    'add' => '新建订单',
                    'update' => '更新订单',
                ),
            ),
            'stock' => array(
                'label' => '库存',
                'methods' => array(
                    'getList' => '库存列表',
                    'update' => '更新库存',
                ),
            ),
        );
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# 3. 参数定义 (lib/api/params/v1/example.php)

<?php
class openapi_api_params_v1_example extends openapi_api_params_abstract implements openapi_api_params_interface
{
    public function checkParams($method, $params, &$sub_msg)
    {
        if(parent::checkParams($method, $params, $sub_msg)){
            return true;
        }else{
            return false;
        }
    }

    public function getAppParams($method)
    {
        $params = array(
            'getList' => array(
                'start_time' => array(
                    'type' => 'date',
                    'required' => 'true',
                    'name' => '开始时间',
                    'desc' => '例如2012-12-08 18:50:30'
                ),
                'end_time' => array(
                    'type' => 'date',
                    'required' => 'true',
                    'name' => '结束时间'
                ),
                'page_no' => array(
                    'type' => 'number',
                    'required' => 'false',
                    'name' => '页码',
                    'desc' => '默认1,第一页'
                ),
                'page_size' => array(
                    'type' => 'number',
                    'required' => 'false',
                    'name' => '每页数量',
                    'desc' => '最大1000'
                ),
            ),
            'add' => array(
                'name' => array(
                    'type' => 'string',
                    'required' => 'true',
                    'name' => '名称'
                ),
                'status' => array(
                    'type' => 'string',
                    'required' => 'false',
                    'name' => '状态',
                    'desc' => '可选值:active, inactive'
                ),
            ),
        );

        return $params[$method];
    }
    
    public function description($method)
    {
        $description = array(
            'getList' => array(
                'name' => '获取列表',
                'description' => '批量获取数据列表'
            ),
            'add' => array(
                'name' => '新建数据',
                'description' => '创建新的数据记录'
            ),
        );
        return $description[$method];
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73

# 4. 功能实现 (lib/api/function/v1/example.php)

<?php
class openapi_api_function_v1_example extends openapi_api_function_abstract implements openapi_api_function_interface
{
    public function getList($params, &$code, &$sub_msg)
    {
        // 参数处理
        $start_time = strtotime($params['start_time']);
        $end_time = strtotime($params['end_time']);
        $page_no = intval($params['page_no']) > 0 ? intval($params['page_no']) : 1;
        $limit = (intval($params['page_size']) > 1000 || intval($params['page_size']) <= 0) ? 100 : intval($params['page_size']);
        
        // 构建过滤条件
        $filter = array();
        if($params['status']) {
            $filter['status'] = $params['status'];
        }
        
        // 分页处理
        if ($page_no == 1) {
            $offset = 0;
        } else {
            $offset = ($page_no - 1) * $limit;
        }
        
        // 获取数据
        $model = app::get('example')->model('example');
        $data = $model->getList('*', $filter, $offset, $limit, 'create_time DESC');
        $total = $model->count($filter);
        
        // 格式化数据
        $result = array();
        foreach($data as $item) {
            $result[] = array(
                'id' => $item['id'],
                'name' => $this->charFilter($item['name']),
                'status' => $this->get_status($item['status']),
                'create_time' => date('Y-m-d H:i:s', $item['create_time']),
                'update_time' => date('Y-m-d H:i:s', $item['update_time']),
            );
        }
        
        return array(
            'lists' => $result,
            'total' => $total,
            'page_no' => $page_no,
            'page_size' => $limit,
        );
    }

    public function add($params, &$code, &$sub_msg)
    {
        // 数据验证
        if(empty($params['name'])) {
            $code = '400';
            $sub_msg = '名称不能为空';
            return false;
        }
        
        // 构建数据
        $data = array(
            'name' => $params['name'],
            'status' => $params['status'] ?: 'active',
            'create_time' => time(),
            'update_time' => time(),
        );
        
        // 保存数据
        $model = app::get('example')->model('example');
        $result = $model->insert($data);
        
        if($result) {
            return array(
                'id' => $result,
                'message' => '创建成功'
            );
        } else {
            $code = '500';
            $sub_msg = '创建失败';
            return false;
        }
    }

    // 辅助方法
    public function get_status($val)
    {
        $types = array(
            'active' => '启用',
            'inactive' => '禁用',
        );
        return $this->charFilter($types[$val]);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92

# 5. 控制器模板 (controller/admin/example.php)

<?php
class openapi_ctl_admin_example extends desktop_controller
{
    public function index()
    {
        $this->page('admin/example/index.html');
    }
    
    public function test()
    {
        // 接口测试逻辑
        $this->pagedata['methods'] = openapi_conf::getMethods();
        $this->page('admin/example/test.html');
    }
    
    public function ajaxResult()
    {
        if(!$_POST['apiName']) return;
        
        $k = substr($_POST['apiName'], 0, strrpos($_POST['apiName'], '.'));
        $function = substr($_POST['apiName'], strrpos($_POST['apiName'], '.')+1);
        
        try{
            $obj = kernel::single('openapi_api_params_v1_'.$k);
        } catch (Throwable $e) {
            list($app, $class) = explode('.', $k);
            $obj = kernel::single($app.'_openapi_params_v1_'.$class);
        }
        
        $list = $obj->getAppParams($function);
        $description = $obj->description($function);
        
        $this->pagedata['list'] = $list;
        $this->pagedata['post'] = $_POST;
        $this->pagedata['description'] = $description;
        
        $this->display('admin/example/apiForm.html');
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

# 📋 开发步骤

# 1. 创建新接口模块

  1. 创建目录结构

    app/openapi/
    ├── lib/api/params/v1/newmodule.php
    ├── lib/api/function/v1/newmodule.php
    └── controller/admin/newmodule.php
    
    1
    2
    3
    4
  2. 配置接口

    • lib/conf.php 中添加接口配置
    • 定义接口方法和描述
  3. 实现参数验证

    • 继承 openapi_api_params_abstract
    • 实现 getAppParams()description() 方法
  4. 实现业务逻辑

    • 继承 openapi_api_function_abstract
    • 实现具体的接口方法
  5. 添加控制器

    • 创建管理界面
    • 实现接口测试功能

# 2. 接口规范

# 参数类型

  • string - 字符串
  • number - 数字
  • date - 日期时间
  • boolean - 布尔值
  • array - 数组

# 响应格式

// 成功响应
return array(
    'lists' => $data,
    'total' => $total,
    'page_no' => $page_no,
    'page_size' => $page_size,
);

// 错误响应
$code = '400';
$sub_msg = '错误信息';
return false;
1
2
3
4
5
6
7
8
9
10
11
12

# 错误码

  • 200 - 成功
  • 400 - 参数错误
  • 401 - 认证失败
  • 403 - 权限不足
  • 404 - 资源不存在
  • 500 - 服务器错误

# 3. 测试接口

  1. 访问测试页面

    /openapi/admin/test
    
    1
  2. 选择接口方法

    • 从下拉列表选择接口
    • 填写参数
    • 点击测试
  3. 查看响应

    • JSON格式响应
    • 错误信息提示

# 🎯 最佳实践

  1. 参数验证: 严格验证输入参数
  2. 错误处理: 统一的错误码和消息
  3. 数据过滤: 使用 charFilter() 过滤特殊字符
  4. 分页处理: 支持分页查询
  5. 性能优化: 合理使用索引和缓存
  6. 文档完善: 详细的接口文档和示例

# 📝 注意事项

  1. 所有接口必须继承相应的抽象类
  2. 参数验证要完整且严格
  3. 响应数据要格式化处理
  4. 错误信息要清晰明确
  5. 接口版本要向后兼容
  6. 敏感数据要加密处理
最后更新: 11/11/2025, 9:12:34 PM