cabreran/ci-hmvc-restserver

CodeIgniter HMVC Rest Server

v3.0.1 2020-07-17 19:51 UTC

This package is auto-updated.

Last update: 2024-09-18 06:02:47 UTC


README

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

要求

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

安装

composer require cabreran/ci-hmvc-restserver

用法

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

"cabreran/ci-hmvc-restserver": "^3.1"

或者运行

composer require cabreran/ci-hmvc-restserver

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

步骤1:将以下代码添加到您的控制器中(应在您的任何代码之前)

use Cabreran\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 Cabreran\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 );
            }
        }
    }
}