presttec/codeigniter-restserver
CodeIgniter Rest Server
dev-master
2020-06-26 21:36 UTC
This package is auto-updated.
Last update: 2024-09-27 07:38:22 UTC
README
使用一个库、一个配置文件和一个控制器实现的CodeIgniter完全RESTful服务器。
要求
- PHP 7.2或更高版本
- CodeIgniter 3.1.11+
安装
composer require presttec/codeigniter-restserver
用法
CodeIgniter Rest Server可在Packagist上找到(使用语义版本控制),并且建议使用composer进行安装。只需将以下行添加到您的composer.json
文件中
"presttec/codeigniter-restserver": "^3.1"
或运行
composer require presttec/codeigniter-restserver
注意,您需要将rest.php
复制到您的config
目录中(例如application/config
)
步骤1:将以下内容添加到您的控制器中(应该在您的代码之前)
use 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 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 ); } } } }