2014年03月25日 星期二 11:37
Restler(2.x版本)是一个非常精巧的REST API Framework,精巧到什么程度呢?它只有一个PHP文件,这个PHP文件只有大约1500行左右,包含非常详细的注释,体积在46KB左右。
只需要这样一个PHP文件,我们就可以将普通的PHP Class封装为标准的REST API,非常简单好用。Restler默认支持JSON结构的数据格式,通过插件扩充,可以支持XML、YAML等等多种数据格式。
Restler的3.x版本目前是RC状态,代码结构比2.x版本要复杂很多。我很喜欢2.x版本的简洁风格,虽然代码年代稍有些久远(最后更新大概是2011年)。
我们首先编写一个计算器的Class(calc.php):
<?php
class Calc {
public $restler;
public function add($a=0,$b=0) {
$this->_validate(func_get_args());
return array("result" => $a+$b);
}
public function sub($a=0,$b=0) {
$this->_validate(func_get_args());
return $a-$b;
}
public function abs($a=0) {
$this->_validate(func_get_args());
return abs($a);
}
private function _validate($numbers) {
foreach($numbers as $num) {
if(!is_numeric($num)) {
throw new RestException(400,"parameter is not a number");
}
if(is_infinite($num)) {
throw new RestException(400,"parameter is not finite");
}
}
}
}
然后编写一个gateway封装(api.php):
<?php
spl_autoload_register('spl_autoload');
$r=new Restler();
//$r->setSupportedFormats('JsonFormat', 'XmlFormat');
$r->addAPIClass('Calc');
$r->handle();
接下来我们就可以通过URL调用Calc的API了,示例URL如下:
http://localhost/restler2/api.php/calc.json/add/1/1
如果启用WEB服务器的URL Rewrite,上面的URL还可以更简洁。
参考资料:
https://github.com/Luracast/Restler/tree/v2
http://help.luracast.com/restler/examples/index.html
Zeuux © 2025
京ICP备05028076号