php处理restful请求的路由类分享
<?php
class router {
// 路由表
private $routers = array(
array("name"=>"userlist", "pattern"=>"get /user", "action"=>"user#get"),
array("name"=>"userinfo", "pattern"=>"get /user/:s", "action"=>"user#getbyid"),
array("name"=>"useradd", "pattern"=>"post /user", "action"=>"user#add"),
array("name"=>"userupdate", "pattern"=>"update /user", "action"=>"user#update"),
array("name"=>"userdel", "pattern"=>"delete /user/:id", "action"=>"user#delete")
);
// 入口
public function dispatch() {
$url = $_server["request_uri"];
$method = $_server["request_method"];
foreach ($this->routers as $router) {
$pattern = $router["pattern"];
$pats = explode(" ", $pattern);
if (strcasecmp($pats[0], $method) == 0) {
// 是否与当前路由匹配
$params = $this->checkurl($method, strtolower($url), strtolower($pats[1]));
if ($params != null) {
array_shift($params);
$action = $router["action"];
// 寻找到第一个匹配的路由即执行,然后返回
return $this->invoke($action, $params);
}
}
}
echo "404 error";
// error 404
}
private function invoke($action, $params) {
$acts = explode("#", $action);
$classname = $acts[0]."action";
$methodname = $acts[1];
$actiondir = dirname(__file__).directory_separator."action";
// 载入action文件
$classfile = $actiondir.directory_separator.$classname.".php";
if (! file_exists($classfile)) {
// 404 error
echo "404 error, no action found";
return;
} else {
require "$classfile";
// 使用反射执行方法
$rc = new reflectionclass($classname);
if (! $rc->hasmethod($methodname)) {
// 404 error
echo "404 error, no method found";
return;
} else {
$instance = $rc->newinstance();
$method = $rc->getmethod($methodname);
$method->invokeargs($instance, $params);
}
}
}
// 正则匹配检查,并提取出参数
private function checkurl($method, $str, $pattern) {
//echo "check $str with $pattern <br>";
$ma = array();
$pattern = ltrim(rtrim($pattern, "/"));
$pattern = "/".str_replace("/", "\/", $pattern)."\/?$/";
$pattern = str_replace(":s", "([^\/]+)", $pattern);
//echo "pattern $pattern<br>";
//$str = "/\".$str."$/";
if (preg_match($pattern, $str, $ma) > 0) {
return $ma;
}
return null;
}
}
?>
上一篇: fast无线USB网卡怎么设置上网?
下一篇: PHP URL参数获取方式的四种例子