mlabate/restful-codeigniter

CodeIgniter 的 Restful 服务器

dev-main 2020-11-01 10:31 UTC

This package is auto-updated.

Last update: 2024-09-29 05:42:56 UTC


README

StyleCI

CodeIgniter 的 RESTful 服务器实现

要求

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

安装

composer require mlabate/restful-codeigniter

使用

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

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

use mlabate\RestServer\RestController;

步骤 2:扩展您的控制器

class Example extends RestController

基本的 GET 示例

以下示例控制器(保存为 Api.php)可以以两种方式调用:<>

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

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