3)使用REST Client類庫訪問
第三種方法是可以使用開源的REST Client類庫(http://github.com/philsturgeon/codeigniter-restclient)去訪問REST,比如同樣上面的代碼,可以寫成:
function rest_client_example($id)
{
$this->load->library("rest", array(
"server" => "http://localhost/restserver/index.php/example_api/",
"http_user" => "admin",
"http_pass" => "1234",
"http_auth" => "basic" // 或者使用"digest"
));
$user = $this->rest->get("user", array("id" => $id), "json");
echo $user->name;
}
看,是不是更簡單了!這里是示例說明了調用GET方法,并且說明返回的形式是JSON的,當然你也可以指定其他形式的返回結果,比如xml,php,csv等,比如:
$user = $this->rest->get("user", array("id" => $id), "application/json");
同理,可以使用$this->rest->post(),$this->rest->put(),$this->rest->delete()等。
最后,我們學習下如何跟twitter的RESTful API打交道,使用RESTful Client library,只需要如下這樣的編寫簡單代碼即可:
$this->load->library("rest", array("server" => "http://twitter.com/"));
$user = $this->rest->get("users/show", array("screen_name" => "philsturgeon"));這個是調用twitter的RESTful API去獲得某個用戶ID的資料,
$this->load->library("rest", array(
"server" => "http://twitter.com/",
"http_user" => "username",
"http_pass" => "password",
"http_auth" => "basic"
));
$user = $this->rest->post("statuses/update.json", array("status" => "Using the REST client to do stuff"));
這個代碼段則是更新某個用戶的狀態。