Blog

PHP Router Function

A self-contained SEF (search engine friendly) routing function, that supports both functions and class methods mapped to routes:

 

function serve($routemap) {

    function findRoute($routemap) {
        $tokens = array(
            ':string' => '([a-zA-Z]+)',
            ':number' => '([0-9]+)',
            ':alpha' => '([a-zA-Z0-9-_]+)'
        );
        krsort($routemap);
        foreach ($routemap as $index => $action) {
            $pattern = strtr($index, $tokens);
            if (preg_match('#^/?' . $pattern . '/?$#', getUri(), $matches)) {
                return array($index, $matches);
            }
        }
        return null;
    }

    if ($result != null) {
        $action = $routemap[$result[0]];
        $actions = explode('@', $action);
        $params = $result[1];
        array_shift($params);
        if (count($actions) > 1) {
            die(call_user_func_array([new $actions[0], $actions[1]], $params));
        } else {
            if (function_exists($actions[0])) {
                die(call_user_func_array($actions[0], $params));
            }
            $class = $actions[0];
            if (isset($actions[1]) == false AND class_exists($class)) {
                $method = count($params) > 0 ? $params[0] : 'home';
                try {
                    $reflectionMethod = new ReflectionMethod($class, $method);
                    if ($reflectionMethod->isPublic() == true) {
                        die($reflectionMethod->invokeArgs(new $class, $params));
                    }
                } catch (Exception $e) {
                    
                }
            }
        }
    }
    die('404 - Page Not Found');
}

 

How to use:

serve([
    '/' => 'home', // using a function
    '/about/' => 'Application@about', // using method in a class
    '/admin/' => 'Admin', // using method in a class
    '/admin/:string' => 'Admin', // using method in a class
    '/admin/blog' => 'AdminBlog', // using method in a class
    '/admin/blog/:string' => 'AdminBlog', // using method in a class
]);