我正在编写一个类来处理我的PHP web服务的路由,但我需要纠正这个正则表达式,并且我想知道什么才是解析url最有效的方法。
示例网址:
POST /使用者
GET / users
GET / users& limit = 10& offset = 0
GET / users / search& keyword = Richard
GET / users / 15 / posts / 38
我想在PHP中为类创建的是:
$router = new Router();
$router->addRoute('POST', '/users', function(){});
$router->addRoute('GET', '/users/:uid/posts/:pid', function($uid, $pid){});
$target = $router->doRouting();目标变量现在将包含一个数组:
方法
URL
回叫方法
这是我到目前为止:
class Router{
use Singleton;
private $routes = [];
private $routeCount = 0;
public function addRoute($method, $url, $callback){
$this->routes[] = ['method' => $method, 'url' => $url, 'callback' => $callback];
$this->routeCount++;
}
public function doRouting(){
$reqUrl = $_SERVER['REQUEST_URI'];
$reqMet = $_SERVER['REQUEST_METHOD'];
for($i = 0; $i < $this->routeCount; $i++){
// Check if the url matches ...
// Parse the arguments of the url ...
}
}
}所以我首先需要一个正则表达式:
/ mainAction /:argumentName / secondaryAction /:secondaryActionName
检查它是否与$ reqUrl匹配(参见上面的for循环)
提取参数,所以我们可以在回调函数中使用它们。
我自己试了一下:
(code should be in the for loop @ doRouting function)
// Extract arguments ...
$this->routing[$i]['url'] = str_replace(':arg', '.+', $this->routing[$i]['url']);
// Does the url matches the routing url?
if(preg_match('#^' . $this->routes[$i]['url'] . '$#', $reqUrl)){
return $this->routes[$i];
}我非常感谢所有帮助,非常感谢。