CodeIgniter RestServer:构建高效RESTful API的利器

CodeIgniter RestServer:构建高效RESTful API的利器

【免费下载链接】codeigniter-restserver 【免费下载链接】codeigniter-restserver 项目地址: https://gitcode.com/gh_mirrors/cod/codeigniter-restserver

还在为CodeIgniter项目构建RESTful API而烦恼?面对复杂的路由配置、繁琐的请求处理、格式转换等问题,传统开发方式往往效率低下。CodeIgniter RestServer库为你提供了一站式解决方案,让你专注于业务逻辑而非底层实现。

通过本文,你将掌握:

  • ✅ RESTful API核心概念与CodeIgniter RestServer优势
  • ✅ 快速安装配置与基础控制器创建
  • ✅ 完整CRUD操作实现与响应格式控制
  • ✅ 高级功能:认证、限流、日志与CORS配置
  • ✅ 实战案例与最佳实践指南

🚀 什么是CodeIgniter RestServer?

CodeIgniter RestServer是一个专为CodeIgniter 3.x设计的RESTful服务器实现库,通过单一库文件、单一配置文件和单一控制器基类,提供了完整的REST API功能支持。

核心特性对比

特性传统方式RestServer方式
路由配置手动配置每个端点自动方法映射
请求解析手动处理不同HTTP方法自动解析与分发
响应格式手动转换JSON/XML等自动多格式支持
认证机制自行实现内置多种认证方式
限流控制需要额外开发内置API限流功能

📦 安装与配置

环境要求

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

Composer安装

composer require chriskacerguis/codeigniter-restserver

配置文件设置

src/rest.php复制到application/config/目录,并根据需要修改配置:

// application/config/rest.php
$config['force_https'] = false;
$config['rest_default_format'] = 'json';
$config['rest_auth'] = false; // 认证方式:false, 'basic', 'digest', 'session'
$config['rest_enable_keys'] = false; // 启用API密钥
$config['rest_enable_logging'] = true; // 启用请求日志

🏗️ 创建第一个REST控制器

基础控制器结构

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

use chriskacerguis\RestServer\RestController;

class Users extends RestController {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('user_model');
    }

    // GET /api/users
    public function index_get()
    {
        $users = $this->user_model->get_all();
        $this->response([
            'status' => true,
            'data' => $users
        ], 200);
    }

    // GET /api/users/{id}
    public function index_get($id = null)
    {
        if ($id === null) {
            $this->index_get();
            return;
        }

        $user = $this->user_model->get($id);
        if ($user) {
            $this->response([
                'status' => true,
                'data' => $user
            ], 200);
        } else {
            $this->response([
                'status' => false,
                'message' => 'User not found'
            ], 404);
        }
    }
}

HTTP方法自动映射

RestServer通过方法后缀自动映射HTTP请求:

mermaid

🔧 完整CRUD实现

用户管理API示例

class Users extends RestController {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('user_model');
    }

    // 获取所有用户 - GET /api/users
    public function index_get()
    {
        $limit = $this->get('limit') ?: 10;
        $offset = $this->get('offset') ?: 0;
        
        $users = $this->user_model->get_all($limit, $offset);
        $total = $this->user_model->count_all();
        
        $this->response([
            'status' => true,
            'data' => $users,
            'pagination' => [
                'limit' => $limit,
                'offset' => $offset,
                'total' => $total
            ]
        ], 200);
    }

    // 创建用户 - POST /api/users
    public function index_post()
    {
        $data = [
            'name' => $this->post('name'),
            'email' => $this->post('email'),
            'created_at' => date('Y-m-d H:i:s')
        ];

        if ($this->user_model->create($data)) {
            $this->response([
                'status' => true,
                'message' => 'User created successfully',
                'data' => $data
            ], 201);
        } else {
            $this->response([
                'status' => false,
                'message' => 'Failed to create user'
            ], 400);
        }
    }

    // 更新用户 - PUT /api/users/{id}
    public function index_put($id)
    {
        $data = [
            'name' => $this->put('name'),
            'email' => $this->put('email'),
            'updated_at' => date('Y-m-d H:i:s')
        ];

        if ($this->user_model->update($id, $data)) {
            $this->response([
                'status' => true,
                'message' => 'User updated successfully'
            ], 200);
        } else {
            $this->response([
                'status' => false,
                'message' => 'Failed to update user'
            ], 400);
        }
    }

    // 删除用户 - DELETE /api/users/{id}
    public function index_delete($id)
    {
        if ($this->user_model->delete($id)) {
            $this->response([
                'status' => true,
                'message' => 'User deleted successfully'
            ], 200);
        } else {
            $this->response([
                'status' => false,
                'message' => 'Failed to delete user'
            ], 400);
        }
    }
}

🌐 多格式响应支持

RestServer支持多种响应格式,自动根据请求头或URL后缀转换:

支持的格式

格式Content-Type说明
JSONapplication/json默认格式,最常用
XMLapplication/xmlXML格式支持
CSVapplication/csv表格数据导出
HTMLtext/htmlHTML表格展示
Arrayapplication/jsonPHP数组格式

格式使用示例

// 强制指定响应格式
$this->rest_format = 'xml';

// 通过URL后缀指定格式
// GET /api/users.xml 返回XML格式
// GET /api/users.json 返回JSON格式

// 通过Accept头指定格式
// Accept: application/xml

🔐 认证与安全

API密钥认证

// 启用API密钥认证
$config['rest_enable_keys'] = true;
$config['rest_keys_table'] = 'api_keys';

// 数据库表结构
CREATE TABLE api_keys (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    key VARCHAR(40) NOT NULL,
    level INT NOT NULL DEFAULT 0,
    ignore_limits TINYINT(1) DEFAULT 0,
    ip_addresses TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Basic认证配置

$config['rest_auth'] = 'basic';
$config['rest_valid_logins'] = [
    'admin' => 'password123',
    'api_user' => 'api_pass'
];

方法级别权限控制

class Users extends RestController {

    public function __construct()
    {
        parent::__construct();
        
        // 设置方法级别限制
        $this->methods['index_get']['limit'] = 100; // 每小时100次请求
        $this->methods['index_get']['key'] = true; // 需要API密钥
        $this->methods['index_post']['level'] = 1; // 需要权限级别1
    }
}

📊 日志与监控

启用请求日志

$config['rest_enable_logging'] = true;
$config['rest_logs_table'] = 'api_logs';

// 日志表结构
CREATE TABLE api_logs (
    id INT AUTO_INCREMENT PRIMARY KEY,
    uri VARCHAR(255) NOT NULL,
    method VARCHAR(6) NOT NULL,
    params TEXT,
    api_key VARCHAR(40),
    ip_address VARCHAR(45) NOT NULL,
    time INT NOT NULL,
    response_time FLOAT,
    authorized TINYINT(1),
    response_code SMALLINT
);

🌍 CORS跨域支持

配置CORS

$config['check_cors'] = true;
$config['allowed_cors_origins'] = [
    'http://localhost:3000',
    'https://yourdomain.com'
];
$config['allowed_cors_methods'] = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'];
$config['allowed_cors_headers'] = ['Origin', 'X-Requested-With', 'Content-Type', 'Accept'];

🚀 性能优化技巧

数据库连接优化

// 使用独立的数据库连接用于API
$config['rest_database_group'] = 'api_db';

// database.php配置
$db['api_db'] = [
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'api_user',
    'password' => 'api_password',
    'database' => 'api_database',
    'dbdriver' => 'mysqli',
    'pconnect' => false, // 避免持久连接
    'cache_on' => false,
    'cachedir' => '',
    'char_set' => 'utf8mb4',
    'dbcollat' => 'utf8mb4_unicode_ci',
    'swap_pre' => '',
    'encrypt' => false,
    'compress' => false,
    'stricton' => false,
    'failover' => []
];

缓存策略

// 在控制器中使用缓存
public function index_get()
{
    $cache_key = 'users_list_' . $this->get('limit') . '_' . $this->get('offset');
    
    if ($cached_data = $this->cache->get($cache_key)) {
        $this->response($cached_data, 200);
        return;
    }
    
    $users = $this->user_model->get_all();
    $response_data = [
        'status' => true,
        'data' => $users
    ];
    
    // 缓存5分钟
    $this->cache->save($cache_key, $response_data, 300);
    $this->response($response_data, 200);
}

🧪 测试与调试

使用cURL测试API

# 获取用户列表
curl -X GET http://localhost/api/users

# 创建新用户
curl -X POST http://localhost/api/users \
  -H "Content-Type: application/json" \
  -d '{"name":"John Doe","email":"john@example.com"}'

# 使用Basic认证
curl -u username:password -X GET http://localhost/api/users

# 使用API密钥
curl -H "X-API-KEY: your_api_key" -X GET http://localhost/api/users

单元测试示例

class Users_test extends TestCase {

    public function test_get_users()
    {
        $output = $this->request('GET', '/api/users');
        $this->assertResponseCode(200);
        
        $data = json_decode($output, true);
        $this->assertTrue($data['status']);
        $this->assertArrayHasKey('data', $data);
    }

    public function test_create_user()
    {
        $post_data = [
            'name' => 'Test User',
            'email' => 'test@example.com'
        ];
        
        $output = $this->request('POST', '/api/users', $post_data);
        $this->assertResponseCode(201);
    }
}

🎯 最佳实践指南

1. 统一的响应格式

// 创建响应辅助方法
protected function success_response($data = null, $message = '', $code = 200)
{
    $response = [
        'status' => true,
        'message' => $message,
        'data' => $data,
        'timestamp' => time()
    ];
    
    $this->response($response, $code);
}

protected function error_response($message, $code = 400, $errors = [])
{
    $response = [
        'status' => false,
        'message' => $message,
        'errors' => $errors,
        'timestamp' => time()
    ];
    
    $this->response($response, $code);
}

2. 输入验证

public function index_post()
{
    $this->form_validation->set_rules('name', 'Name', 'required|min_length[2]');
    $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
    
    if ($this->form_validation->run() === FALSE) {
        $this->error_response('Validation failed', 422, $this->form_validation->error_array());
        return;
    }
    
    // 处理有效数据...
}

3. 异常处理

public function index_get($id = null)
{
    try {
        if ($id) {
            $user = $this->user_model->get_or_fail($id);
            $this->success_response($user);
        } else {
            $users = $this->user_model->get_all();
            $this->success_response($users);
        }
    } catch (ModelNotFoundException $e) {
        $this->error_response('User not found', 404);
    } catch (Exception $e) {
        log_message('error', $e->getMessage());
        $this->error_response('Server error', 500);
    }
}

📈 性能监控指标

指标建议值监控方法
响应时间< 200ms日志中的rtime字段
错误率< 1%响应码统计
吞吐量根据业务需求请求计数
缓存命中率> 80%缓存统计

🔮 未来发展与升级

迁移到CodeIgniter 4

mermaid

CodeIgniter 4已经内置了RESTful支持,建议新项目直接使用CI4。对于现有CI3项目,可以继续使用RestServer,并制定逐步迁移计划。

🎉 总结

CodeIgniter RestServer为CI3开发者提供了强大而灵活的REST API开发体验。通过本文的全面介绍,你应该已经掌握了:

  • ✅ 快速搭建RESTful API基础设施
  • ✅ 实现完整的CRUD操作与多格式响应
  • ✅ 配置认证、限流、日志等高级功能
  • ✅ 应用性能优化与最佳实践
  • ✅ 制定测试策略与监控方案

无论你是构建内部微服务还是面向公众的开放API,CodeIgniter RestServer都能为你提供可靠的技术 foundation。立即开始你的RESTful API开发之旅吧!

下一步行动:

  1. 安装RestServer库并创建第一个API端点
  2. 配置数据库连接和认证机制
  3. 实现业务逻辑并添加测试用例
  4. 部署到生产环境并设置监控

祝你编码愉快! 🚀

【免费下载链接】codeigniter-restserver 【免费下载链接】codeigniter-restserver 项目地址: https://gitcode.com/gh_mirrors/cod/codeigniter-restserver

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值