首页
/ CodeIgniter RestServer 技术文档

CodeIgniter RestServer 技术文档

2024-12-23 12:23:33作者:伍霜盼Ellen

1. 安装指南

环境要求

  • PHP 7.2 或更高版本
  • CodeIgniter 3.1.11 或更高版本

安装步骤

  1. 使用 Composer 安装 CodeIgniter RestServer:

    composer require chriskacerguis/codeigniter-restserver
    
  2. rest.php 配置文件复制到你的 application/config 目录下。

2. 项目的使用说明

基本使用步骤

  1. 在你的控制器文件中引入 RestController 类:

    use chriskacerguis\RestServer\RestController;
    
  2. 继承 RestController 类:

    class Example extends RestController {
        // 你的代码
    }
    

基本 GET 示例

以下是一个基本的 GET 请求示例。该控制器文件应保存为 Api.php,可以通过以下两种方式调用:

  • http://domain/api/users/ 返回所有用户列表
  • http://domain/api/users/id/1 返回 ID 为 1 的用户信息
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

use chriskacerguis\RestServer\RestController;

class Api extends RestController {

    function __construct()
    {
        // 构造父类
        parent::__construct();
    }

    public function users_get()
    {
        // 从数据存储中获取用户数据,例如数据库
        $users = [
            ['id' => 0, 'name' => 'John', 'email' => 'john@example.com'],
            ['id' => 1, 'name' => 'Jim', 'email' => 'jim@example.com'],
        ];

        $id = $this->get( 'id' );

        if ( $id === null )
        {
            // 检查用户数据存储中是否包含用户
            if ( $users )
            {
                // 设置响应并退出
                $this->response( $users, 200 );
            }
            else
            {
                // 设置响应并退出
                $this->response( [
                    'status' => false,
                    'message' => 'No users were found'
                ], 404 );
            }
        }
        else
        {
            if ( array_key_exists( $id, $users ) )
            {
                $this->response( $users[$id], 200 );
            }
            else
            {
                $this->response( [
                    'status' => false,
                    'message' => 'No such user found'
                ], 404 );
            }
        }
    }
}

3. 项目API使用文档

API 请求示例

  • GET 请求
    • 获取所有用户:http://domain/api/users/
    • 获取特定用户:http://domain/api/users/id/1

响应格式

  • 成功响应

    [
        {
            "id": 0,
            "name": "John",
            "email": "john@example.com"
        },
        {
            "id": 1,
            "name": "Jim",
            "email": "jim@example.com"
        }
    ]
    
  • 错误响应

    {
        "status": false,
        "message": "No users were found"
    }
    

4. 项目安装方式

使用 Composer 安装

composer require chriskacerguis/codeigniter-restserver

手动安装

  1. 下载项目源码。
  2. rest.php 配置文件复制到 application/config 目录下。
  3. 在你的控制器中引入并继承 RestController 类。
登录后查看全文
热门项目推荐
相关项目推荐