步驟3 分析example_api.php
接下來,我們打開application/controllers/example_api.php文件,仔細分析其代碼。
首先,在CodeIgniter中,我們要繼承CodeIgniter框架本身的REST_Controller.php(這個文件位于libraries目錄中),如下所示:
require(APPPATH".libraries/REST_Controller.php");
class Example_api extends REST_Controller {
}
接著我們看其中兩個獲得資源的方法,分別是user_get()和users_get(),其中user_get()是根據用戶id去獲得某個用戶的信息,而users_get()則獲得多個用戶的信息,代碼框架如下:
php
require(APPPATH".libraries/REST_Controller.php");
class Example_api extends REST_Controller {
function user_get()
{
// 獲得一個用戶的信息
}
function users_get()
{
//獲得多個用戶的信息
}
}
接著我們復習下在RESTful架構中的四類關于資源的操作。
GET:
使用GET去獲得一個已經存在的資源的信息。通常我們在瀏覽器中輸入url其實即發出了一個GET的請求。
POST:
使用POST去更新一個已經存在的資源。比如表單中的提交數據行為,都屬于POST類型。
PUT:
使用HTTP的報文頭的PUT,可以去新建一種資源,目前不是所有瀏覽器支持,所以本文不作討論。
DELETE:
使用DELETE去刪除一種資源,同樣目前不是所有瀏覽器都支持。
現在我們可以根據四種HTTP RESTful語義去形成如下框架:
require(APPPATH".libraries/REST_Controller.php");
class Example_api extends REST_Controller {
function user_get()
{
// 獲得一個用戶的信息
}
function user_put()
{
// 創建一個新用戶
}
function user_post()
{
//更新用戶信息
}
function user_delete()
{
//刪除用戶信息
}
}
接下來我們充分利用CodeIgniter框架自身的REST_Controller的優勢,完善為如下代碼:
php
require(APPPATH".libraries/REST_Controller.php");
class Example_api extends REST_Controller {
function user_get()
{
$data = array("returned: ". $this->get("id"));
$this->response($data);
}
function user_post()
{
$data = array("returned: ". $this->post("id"));
$this->response($data);
}
function user_put()
{
$data = array("returned: ". $this->put("id"));
$this->response($data;
}
function user_delete()
{
$data = array("returned: ". $this->delete("id"));
$this->response($data);
}
}
以上代碼中包含了如下幾個片段,下面逐一講解:
$this->get() 其中,使用這個從形如index.php/example_api/user?id=1或者如index.php/example_api/user /id/1的連接中獲得資源,比如這里就獲得其id的值,然后在數組中返回該id對應的數值。
$this->post() 其實是CodeIgniter中調用了其框架的$this->input->post()方法,進行提交操作,并且利用了XSS保護特性。
$this->put() 取curl中提交的或者HTTP協議頭的PUT參數的內容。
$this->delete() 取curl中提交的或者HTTP協議頭的delete參數的內容。
$this->response() 個方法中,主要是將處理的數據返回給瀏覽器,你可以指定一個HTTP狀態碼去表示該次返回結果的狀態,比如在數據庫中找不到某個記錄,可以使用如$this->response(array("error" => "User not found.")去返回結果。
步驟4 與現有應用整合
在下載的示例程序中,我們剛才講解了重要的部分,接下來講解如何將下載程序中的關鍵類與現有的應用整合。下載的應用中,結構如下圖: