CodeIgniter Rest Server 學(xué)習(xí)筆記
什么是CodeIgniter Rest Server谭羔?
利用一個庫文件、一個配置文件以及一個控制器就可以實(shí)現(xiàn)完整的CodeIgniter
開發(fā)RESTful
架構(gòu)API
的一個工具痘煤。
Installation
只需要向CodeIgniter
文件夾中的composer.json
文件添加一下代碼:
"chriskacerguis/codeigniter-restserver": "^3.0"
然后運(yùn)行一下命令安裝依賴包:
composer install
Handling Requests
當(dāng)你的控制器繼承REST_Controller
的時候,這個控制器中的方法名之后應(yīng)該跟著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
請求動詞嫉父,可以通過以下方法來獲取參數(shù):
$this->get('blah'); // GET param
$this->post('blah'); // POST param
$this->put('blah'); // PUT param
而對于DELETE
請求,則只能通過在方法中添加參數(shù)眼刃,然后通過URL
傳入?yún)?shù)绕辖,來進(jìn)行訪問:
public function index_delete($id)
{
$this->response([
'returned from delete:' => $id,
]);
}
無論請求是否為GET請求,只要是通過URL傳入的參數(shù)擂红,都可以通過以下方法獲取參數(shù):
$this->query('blah'); // Query param
Responses
可以通過類提供的response()
方法來返回任意數(shù)據(jù):
public function index_get()
{
$this->response($this->db->get('books')->result());
}
若成功返回仪际,那么它將會自動帶上一個HTTP 200 OK
狀態(tài)碼,你也可以通過response()
方法的第二個參數(shù)來自定義返回的狀態(tài)碼:
public function index_post()
{
// ...create new book
$this->response($book, 201); // Send an HTTP 201 Created
}
如果你沒有設(shè)置一個自定義的狀態(tài)碼昵骤,并且返回的數(shù)據(jù)出錯了(空數(shù)組或者是空串)树碱,那么狀態(tài)碼將會被自動設(shè)置為404 Not Found
:
$this->response([]); // HTTP 404 Not Found