yidas / codeigniter-rest
CodeIgniter 3 RESTful API 资源基控制器
Requires
- php: >=5.4.0
README
CodeIgniter RESTful API
CodeIgniter 3 RESTful API 资源基控制器
这个RESTful API扩展被收集到yidas/codeigniter-pack中,这是一个完整的Codeigniter框架解决方案。
特性
-
PSR-7 标准化
-
RESTful API 实现
-
Laravel 资源控制器 模式
概述
演示
class ApiController extends yidas\rest\Controller { public function index() { return $this->response->json(['bar'=>'foo']); } }
状态 200 OK
的输出
{"bar":"foo"}
RESTful 创建回调
public function store($requestData=null) { $this->db->insert('mytable', $requestData); $id = $this->db->insert_id(); return $this->response->json(['id'=>$id], 201); }
状态 201 Created
的输出
{"id":1}
打包标准格式
try { throw new Exception("API forbidden", 403); } catch (\Exception $e) { // Pack data into a standard format $data = $this->pack(['bar'=>'foo'], $e->getCode(), $e->getMessage()); return $this->response->json($data, $e->getCode()); }
状态 403 Forbidden
的输出
{"code":403,"message":"API forbidden","data":{"bar":"foo"}}
要求
此库需要以下内容
- PHP 5.4.0+
- CodeIgniter 3.0.0+
安装
在您的Codeigniter项目中的 \application
文件夹下运行Composer
composer require yidas/codeigniter-rest
检查Codeigniter application/config/config.php
$config['composer_autoload'] = TRUE;
您可以将供应商路径自定义到
$config['composer_autoload']
配置
- 创建一个控制器,扩展
yidas\rest\Controller
,
class Resource extends yidas\rest\Controller {}
- 添加并实现通过 构建方法 引用的操作方法。
然后您就可以访问RESTful API了
https://yourname.com/resource/api
https://yourname.com/resource/api/123
如果您喜欢,您也可以使用 /ajax
而不是 /api
https://yourname.com/resource/ajax
https://yourname.com/resource/ajax/123
resource
是控制器名称,如果您不想在URI中有/api
或/ajax
,您可以设置以下路由设置。
路由设置
如果您想有一个标准的RESTful URI模式,该控制器将其定义为URI资源,例如
https://yourname.com/resource
https://yourname.com/resource/123
您可以在 \application\config\routes.php
中添加一对路由,以启用RESTful API URL
$route['resource_name'] = '[Controller]/route'; $route['resource_name/(:any)'] = '[Controller]/route/$1';
资源控制器
基本的RESTful API控制器是 yidas\rest\Controller
,以下表格是资源控制器处理的行为,action
指的是 CI_Controller
的动作名称,您可以覆盖它
没有路由设置的情况下,URI类似于
/photos/api
&/photos/api/{photo}
。
构建方法
您可以通过参考 资源控制器模板 来创建资源控制器。
以下RESTful控制器方法可以根据您的需求添加。每个方法默认对应资源控制器表中的动作,并注入所需参数
public function index() {} protected function store($requestData=null) {} protected function show($resourceID) {} protected function update($resourceID=null, $requestData=null) {} protected function delete($resourceID=null, $requestData=null) {}
$resourceID
(字符串) 是从请求中地址的资源标识
$requestData
(数组) 是从请求原始体解析的数组输入数据,支持常见的内容类型数据格式。(或者使用this->request->getRawBody()
获取原始数据)
自定义路由和方法
以下是为映射资源控制器相同动作方法的默认路由
protected $routes = [ 'index' => 'index', 'store' => 'store', 'show' => 'show', 'update' => 'update', 'delete' => 'delete', ];
您可以在创建资源控制器时覆盖它来定义自己的路由
class ApiController extends yidas\rest\Controller { protected $routes = [ 'index' => 'find', 'store' => 'save', 'show' => 'display', 'update' => 'edit', 'delete' => 'destory', ]; }
在重置路由后,每个RESTful方法(键)都会进入指定的控制器动作(值)。在上面的示例中,当通过 GET
方法访问 /resources/api/
URL时,会进入 find()
动作。但是,默认路由会进入 index()
动作。
键指的是资源控制器表中的操作,您必须定义所有需要的所有方法。
行为
资源控制器支持为每个操作设置行为,您可以实现如不同权限的认证等。
_setBehavior()
在路由之前设置行为
protected boolean _setBehavior(string $action, callable $function)
示例
class BaseRestController extends \yidas\rest\Controller { function __construct() { parent::__construct(); // Load your Auth library for verification $this->load->library('Auth'); $this->auth->verify('read'); // Set each action for own permission verification $this->_setBehavior('store', function() { $this->auth->verify('create'); }); $this->_setBehavior('update', function() { $this->auth->verify('update'); }); $this->_setBehavior('delete', function() { $this->auth->verify('delete'); }); } // ...
使用
pack()
将数组数据打包成主体格式
您可以为应用程序的标准覆盖此方法。
protected array pack(array|mixed $data, integer $statusCode=200, string $message=null)
示例
$data = $this->pack(['bar'=>'foo'], 403, 'Forbidden'); return $this->response->json($data, 403);
JSON 结果
{
"code": 403,
"message": "Forbidden",
"data": {
"bar": "foo"
}
}
HTTP 请求
PSR-7 请求组件 yidas\http\request
已预载入到 yidas\rest\Controller
,这提供了输入处理和 HTTP 认证。您可以在控制器类中通过 $this->request
调用它。
使用
getRawBody()
返回原始 HTTP 请求主体
public string getRawBody()
示例
// Request with `application/json` raw $data = json_decode($this->request->getRawBody);
getAuthCredentialsWithBasic()
使用 HTTP Basic 认证获取凭据
public array getAuthCredentialsWithBasic()
示例
list($username, $password) = $this->request->getAuthCredentialsWithBasic();
getAuthCredentialsWithBearer()
使用 OAuth 2.0 授权框架:Bearer 令牌使用获取凭据
public string getAuthCredentialsWithBearer()
示例
$b64token = $this->request->getAuthCredentialsWithBearer();
HTTP 响应
PSR-7 响应组件 yidas\http\response
已预载入到 yidas\rest\Controller
,它提供了输出处理和格式化。您可以在控制器类中通过 $this->response
调用它。
使用
json()
JSON 输出快捷方式
public void json(array|mixed $data, integer $statusCode=null)
示例
$this->response->json(['bar'=>'foo'], 201);
setFormat()
将响应格式设置为 CI_Output
public self setFormat(string $format)
示例
$this->response->setFormat(\yidas\http\Response::FORMAT_JSON);
setData()
将响应数据设置为 CI_Output
public self setData(mixed $data)
示例
$this->response->setData(['foo'=>'bar']);
send()
将响应发送到客户端。
public void send()
示例
$this->response->send();
withAddedHeader()
返回一个具有指定值附加的给定头部的实例。
public self withAddedHeader(string $name, string $value)
示例
return $this->response ->withAddedHeader('Access-Control-Allow-Origin', '*') ->withAddedHeader('X-Frame-Options', 'deny') ->json(['bar'=>'foo']);