schema31 / php-ci-restserver
CI Rest Server
3.1.3
2020-11-24 13:54 UTC
This package is auto-updated.
Last update: 2024-09-24 22:10:53 UTC
README
使用一个库、一个配置文件和一个控制器实现的针对 CodeIgniter 的完整 RESTful 服务器实现。
要求
- PHP 7.2 或更高版本
- CodeIgniter 3.1.11+
安装
composer require schema31/php-ci-restserver
用法
CodeIgniter Rest Server 可在 Packagist 上找到(使用语义化版本),并且推荐通过 composer 安装 Codeigniter Rest Server。只需将以下行添加到您的 composer.json 文件中
"schema31/php-ci-restserver": "^3.1"
或运行
composer require schema31/php-ci-restserver
注意,您需要将 rest.php 复制到您的 config 目录(例如 application/config)
步骤 1:将以下内容添加到您的控制器中(应在任何代码之前)
use Schema31\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 Schema31\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 ); } } } }