https://www.laruence.com/manual/yaf.routes.custom.html
yaf的框架介绍:
https://www.laruence.com/manual/
restful api介绍:
https://www.ruanyifeng.com/blog/2014/05/restful_api.html
本文起点定在使用yaf搭建好hello world页面。
对于restful api的接口,有两种方式实现,
第一种是自定义路由[https://www.laruence.com/manual/yaf.routes.custom.html]:
示例如下:
class Helper_Router extends Yaf_Request_Abstract implements Yaf_Route_Interface{
public function route($request ){
}
public function assemble (array $mvc, array $query = NULL){
}
}
然后Bootstrp.php加载这个路由即可
第二种使用插件机制,Bootstap加载路由插件
例如api接口:
PUT /zoos/ID
对于http接口的请求可以使用Yaf_Request_Abstract [https://www.laruence.com/manual/yaf.class.request.html]
对应自定义路由中的route函数,使用
$request->getMethod(); 获取 HTTP方法 这里是 “POST"
$request->getRequestUri(); 获取链接 这里是 "/zoos/ID"
通过固定规则的然后使用
$request->setModuleName(...);
$request->setControllerName(...);
$request->setActionName(...);
即可调用对应的规则
示例代码:
支持POST/DELETE/GET/PUT
/zoos/animals/:id?offset=:offset&limit=:limit 类似
public function route($request ){
$method = $request->getMethod();
$uri = $request->getRequestUri();
//首先验证method是否合法
$check_method = strtolower($method);
$allow_method = array('get', 'post', 'put', 'delete');
if(! in_array($check_method, $allow_method)){
throw new Yaf_Exception("{$method} not supported", 405);
}
$uri = ltrim($uri, '/');
$uri_cut = explode('/', $uri);
if(count($uri_cut) < 2){
throw new Yaf_Exception('not exits method', 400);
}
if(count($uri_cut) == 2){
$param = 0;
list($module, $control) = $uri_cut;
}else{
list($module, $control, $param) = $uri_cut;
}
$controller = ucfirst(strtolower($control)) . "_" . ucfirst(strtolower($method));
$request->setModuleName(strtoupper($module));
$request->setControllerName($controller);
$request->setActionName('index');
$request->setParam("id", htmlspecialchars($param, ENT_QUOTES));
}