Last active
August 29, 2015 14:01
-
-
Save bitsmanent/2a7fecc4ab89cffe4628 to your computer and use it in GitHub Desktop.
Simple routing system
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function route($method, $route, $func = null) { | |
static $routes = array(); | |
if(!$func) { | |
$r = null; | |
$n = ''; | |
$argv = array(); | |
foreach(explode('/', $route) as $arg) { | |
$n .= ($n == '/' ? $arg : "/$arg"); | |
if($r) | |
$argv[] = $arg; | |
if(isset($routes[$method][$n])) { | |
$r = $routes[$method][$n]; | |
$argv = array(); | |
if($route == $n) | |
break; | |
} | |
if(isset($routes[$method]["$n/"])) { | |
$r = $routes[$method]["$n/"]; | |
$argv = array(); | |
} | |
} | |
if(!$r) | |
die('No route found.'); | |
if(count($argv) < $r['mandatory']) | |
die('Missing arguments'); | |
if(count($argv) > $r['argc']) | |
die('Too many arguments'); | |
return call_user_func_array($r['func'], $argv); | |
} | |
$name = array(); | |
$argc = 0; | |
$mandatory = 0; | |
foreach(explode('/', $route) as $arg) { | |
switch(@$arg[0]) { | |
case '!': ++$argc; ++$mandatory; break; | |
case '?': ++$argc; break; | |
default: $name[] = $arg; break; | |
} | |
} | |
$name = implode('/', $name); | |
if($argc) | |
$name .= '/'; | |
$routes[$method][$name] = array('func' => $func, 'argc' => $argc, 'mandatory' => $mandatory); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment