wangshixiang/codeigniter-restserver

CI Rest Server

3.1.2 2020-06-17 01:50 UTC

README

StyleCI

使用一个库、一个配置文件和一个控制器实现 CodeIgniter 的完全 RESTful 服务器。

要求

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

安装

composer require chriskacerguis/codeigniter-restserver

用法

CodeIgniter Rest Server 可在 Packagist 上找到(使用语义版本控制),通过 composer 安装 Codeigniter Rest Server 是推荐的方式。只需将以下行添加到您的 composer.json 文件中

"chriskacerguis/codeigniter-restserver": "^3.1"

或运行

composer require chriskacerguis/codeigniter-restserver

注意,您需要将 rest.php 复制到您的 config 目录中(例如 application/config

步骤 1:将此代码添加到您的控制器中(应该在您的代码之前)

use chriskacerguis\RestServer\RestController;

步骤 2:扩展您的控制器

class Example extends RestController

基本的 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()
    {
        // Construct the parent class
        parent::__construct();
    }

    public function users_get()
    {
        // Users from a data store e.g. database
        $users = [
            ['id' => 0, 'name' => 'John', 'email' => 'john@example.com'],
            ['id' => 1, 'name' => 'Jim', 'email' => 'jim@example.com'],
        ];

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

        if ( $id === null )
        {
            // Check if the users data store contains users
            if ( $users )
            {
                // Set the response and exit
                $this->response( $users, 200 );
            }
            else
            {
                // Set the response and exit
                $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 );
            }
        }
    }
}