CodeIgniter Rest Server 学习笔记
什么是CodeIgniter Rest Server?
利用一个库文件、一个配置文件以及一个控制器就可以实现完整的CodeIgniter
开发RESTful
架构API
的一个工具。
Installation
只需要向CodeIgniter
文件夹中的composer.json
文件添加一下代码:
"chriskacerguis/codeigniter-restserver": "^3.0"
然后运行一下命令安装依赖包:
composer install
Handling Requests
当你的控制器继承REST_Controller
的时候,这个控制器中的方法名之后应该跟着HTTP请求动词,例如:
require 'application/vendor/autoload.php';
class Books extends REST_Controller
{
public function index_get()
{
// Display all books
}
public function index_post()
{
// Create a new book
}
}
对于PUT
、GET
、POST
等HTTP
请求动词,可以通过以下方法来获取参数:
$this->get('blah'); // GET param
$this->post('blah'); // POST param
$this->put('blah'); // PUT param
而对于DELETE
请求,则只能通过在方法中添加参数,然后通过URL
传入参数,来进行访问:
public function index_delete($id)
{
$this->response([
'returned from delete:' => $id,
]);
}
无论请求是否为GET请求,只要是通过URL传入的参数,都可以通过以下方法获取参数:
$this->query('blah'); // Query param
Responses
可以通过类提供的response()
方法来返回任意数据:
public function index_get()
{
$this->response($this->db->get('books')->result());
}
若成功返回,那么它将会自动带上一个HTTP 200 OK
状态码,你也可以通过response()
方法的第二个参数来自定义返回的状态码:
public function index_post()
{
// ...create new book
$this->response($book, 201); // Send an HTTP 201 Created
}
如果你没有设置一个自定义的状态码,并且返回的数据出错了(空数组或者是空串),那么状态码将会被自动设置为404 Not Found
:
$this->response([]); // HTTP 404 Not Found