php 使用 restler 框架構建 restfull api
restler 輕量級,小巧,構建restfull api非常方便!
官網:http://restler3.luracast.com/
目前最后的是3.0版本,我測試使用的是2.2版本;
一:安裝restler2
1. 下載 https://github.com/Luracast/Restler/tree/2.2.0
2. exmple目錄下放的是例子
3. 把restler 目錄的所有文件放到你的web服務下;
二:開始創建restfull api
1. index.php
<?php
//引入restler庫
require_once './restler/restler.php';
$r = new Restler();
//配置支持的返回數據格式,json,xml等
$r->setSupportedFormats('JsonFormat');
//接口列表文件
$r->addAPIClass('api');
$r->handle();
?>
2. 主接口文件 api.php, 上述1中的api表示的類名api
<?php
//工具類
include 'util.php';
class api
{
//get 請求 /url/xml
public function getXml($deviceType)
{
if (!$deviceType) {
return array('xml' =>"error ");
}
if ($deviceType=='1') {
//return ios
return array('xml' =>"ios");
}
elseif ($deviceType=='2') {
//return android
return array('xml' =>"android");
}
elseif ($deviceType=='3') {
//return pc
return array('xml' =>"pc");
}
else
{
return array('xml' =>"none support deviceType");
}
}
//post 請求,
public function postXXL($dev)
{
return returnXML($dev);
}
//當類名與文件名相同時,可以不用 include 該類
public function getAAA()
{
$bd = new Baidu();
return $ret = array('site' => "baidu.com", );;
}
}
?>
三:訪問測試
1. api.php中所有public的方法,就是請求的方法,get或post 以方法名的前關鍵字為准;
如getXml方法,測試請求方式為
get http://127.0.0.1/tp/api/xml.josn
或 http://127.0.0.1/tp/api/xml/1.json
或http://127.0.0.1/tp/api/xml?deviceType=1
后面的1對應getXml的請求字段 $deviceType
2. 其他函數同上
3. 如果要同時支持xml
如http://127.0.0.1/tp/api/xml/1.xml
http://127.0.0.1/tp/api/xml/1.json
在index.php配置
$r->setSupportedFormats('JsonFormat', 'XmlFormat');
更多:http://restler3.luracast.com/examples/index.html
