鍍金池/ 問答/PHP/ noahbuscher/macaw組建的一個疑問,求解答

noahbuscher/macaw組建的一個疑問,求解答

今天看一個路由包的源碼,覺得這步判斷有點(diǎn)多余,希望大家可以幫助理解下這塊的源碼。

項(xiàng)目地址:https://github.com/noahbusche...

這個包很小,下面是主要代碼部分,不理解為何有了(in_array($uri, self::$routes))這個if判斷,還需要下面的(preg_match('#^' . $route . '$#', $uri, $matched))正則判斷,這倆判斷從結(jié)果上有什么不同么

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;
                 ...
            }
        }
    }
}
回答
編輯回答
憶往昔
Macaw::get('page', 'Controllers\demo@page');//路由1
Macaw::get('view/(:num)', 'Controllers\demo@view');//路由2

如果url=http://xxx.com/page
可以用in_array匹配到路由1

但是如果url=http://xxx.com/view/1
就無法用in_array匹配到路由2
所以只能用正則

2018年6月28日 14:52