An answer to a question created by noahbuscher/macaw

Today, looking at the source code of a routing packet, I think this judgment is a bit superfluous. I hope you can help understand the source code of this block.

Project address: https://github.com/noahbusche.

this package is very small, the following is the main part of the code, do not understand why there is (in_array ($uri, self::$routes)) this if judgment, but also need the following (preg_match ("- sharp ^"). $route. "$- sharp", $uri, $matched)) regular judgment, are there any differences between these two judgments in terms of results

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("-sharp^" . $route . "$-sharp", $uri, $matched)) {
            if (self::$methods[$pos] == $method || self::$methods[$pos] == "ANY" || (!empty(self::$maps[$pos]) && in_array($method, self::$maps[$pos]))) {
                $found_route = true;
                 ...
            }
        }
    }
}
Mar.07,2021

Macaw::get('page', 'Controllers\demo@page');//1
Macaw::get('view/(:num)', 'Controllers\demo@view');//2

if url= http://xxx.com/page
can use in_array to match to Route 1

but if url= http://xxx.com/view/1
cannot use in_array to match to Route 2
, you can only use regular

.
Menu