完成Apache + PHP的架設後,筆者使用CodeIgniter架設RESTful web service
環境說明
1. 安裝CodeIgniter
從
官網下載,目前的版本是2.1.4
解壓縮並放到網站根目錄,接著把資料夾名字改成網站名稱(筆者以ws作為網站目錄)
用瀏覽器開啟http://127.0.0.1/~user/ws 試試看CodeIgniter能不能正常執行
2. 設定CodeIgniter Rest Server
從GitHub上下載
codeigniter-restserver並放到家目錄中,解壓縮後以下檔案放到對應的資料夾中
//切換到解壓縮後的codeigniter-restservice下
Shiun@ShiunMac ~ cd codeigniter-restserver-master
//複製Format.php到網站資料夾下
Shiun@ShiunMac ~/codeigniter-restserver-master cp application/libraries/Format.php ~/Sites/ws/application/libraries/
// 同上,複製REST_Controller.php和reset.php到對應的目錄下
Shiun@ShiunMac ~/codeigniter-restserver-master cp application/libraries/REST_Controller.php ~/Sites/ws/application/libraries/
// rest.php
Shiun@ShiunMac ~/codeigniter-restserver-master cp application/config/rest.php ~/Sites/ws/application/config/
將web service預設的輸出格式改成JSON
// 移動到網站資料夾
Shiun@ShiunMac ~/codeigniter-restserver-master cd ~/Sites/ws
// 修改rest.php
Shiun@ShiunMac ~/Sites/ws vi application/config/rest.php
3. 撰寫Web Service程式碼
使用codeigniter-restserver撰寫程式碼只需要在function名稱的後面加上對應的_get, _post, _put, _delete即可
例如實作index_get, index_post的function後即可對http://127.0.0.1/~shiun/ws/index.php/service/index 進行GET和POST的request
廢話不多說,以下是GET, POST, PUT, DELETE的範例
i. GET
Shiun@ShiunMac ~/Sites/ws vi application/controller/Service.php
<?php
require APPPATH.'/libraries/REST_Controller.php';
class Service extends REST_Controller {
public function index_get() {
$data = array(
"key1" => "value1",
"key2" => "value2",
"Method" => "GET",
);
$this->response($data);
}
}
?>
ii. POST
public function index_post() {
$value1 = $this->post("key1");
$value2 = $this->post("key2");
$res = array(
"key1" => $value1,
"key2" => $value2,
"Method" => "POST",
);
$this->response($res, 200);
}
iii. PUT
public function index_put() {
$value1 = $this->put("key1");
$value2 = $this->put("key2");
$res = array(
"key1" => $value1,
"key2" => $value2,
"Method" => "PUT",
);
$this->response($res, 200);
}
iv. DELETE
public function index_delete($id) {
$res = array(
"id" => $id,
"Method" => "DELETE",
);
$this->response($res, 200);
}
4. 測試RESTful web service是否架設成功
筆者使用Firefox的外掛
RESTClient測試以上的程式是否正確
啟動RESTClient後請先加入Content-Type: application/json這個header
加入成功後會顯示以下畫面
接著首先來測試GET
選擇Method: GET並填上URL: http://127.0.0.1/~shiun/ws/index.php/service/index 再來按下Send即可在Response欄位中看到結果
再來測試POST
選擇Method: POST,URL維持不變但body中填入JSON格式的key1和key2參數,接著按下SEND就可以看到結果~
剩下的PUT和DELETE也可以透過一樣的方式測試因此筆者不再贅述
參考資料
1.
CodeIgniter繁體中文官方網站