今天看一个路由包的源码,觉得这步判断有点多余,希望大家可以帮助理解下这块的源码。
项目地址:https://github.com/noahbusche...
这个包很小,下面是主要代码部分,不理解为何有了(in_array($uri, self::$routes))这个if判断,还需要下面的(preg_match('#^' . $route . '$#', $uri, $matched))正则判断,这俩判断从结果上有什么不同么
if (in_array($uri, self::$routes)) {
$route_pos = array_keys(self::$routes, $uri);
foreach ($route_pos as $route) {
// Using an ANY option to match both GET and POST requests
if (self::$methods[$route] == $method || self::$methods[$route] == 'ANY' || in_array($method, self::$maps[$route])) {
$found_route = true;
...
}
}
} else {
// Check if defined with regex
$pos = 0;
foreach (self::$routes as $route) {
if (strpos($route, ':') !== false) {
$route = str_replace($searches, $replaces, $route);
}
if (preg_match('#^' . $route . '$#', $uri, $matched)) {
if (self::$methods[$pos] == $method || self::$methods[$pos] == 'ANY' || (!empty(self::$maps[$pos]) && in_array($method, self::$maps[$pos]))) {
$found_route = true;
...
}
}
}
}