-
-
Save mjburgess/6397377 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
<?php | |
/** | |
* Basic dispatch function, uses array structured as [$verb => [$path => $route_fn, ...]] | |
* calling $route_fn if $path/$verb match the arguments passed | |
* | |
* @param $path_condition regex for matching paths (must use suitable deliminator, eg. @) | |
* | |
* @throws Exception when path/route function missing (programmer error) | |
* @return bool true for successful route, false for no route/404 | |
*/ | |
function web_app(array $routes, $verb, $path, $path_condition = '@%s@i') { | |
$path = trim(parse_url($path, PHP_URL_PATH), '/'); | |
if(empty($routes[$verb])) { | |
return false; | |
} | |
foreach ($routes[$verb] as $route_path => $route_fn) { | |
if(empty($route_path) || empty($route_fn)) { | |
throw new Exception('Route Path and Function requred!'); | |
} | |
if (preg_match(sprintf($path_condition, trim($route_path, '/')), $path, $captured)) { | |
call_user_func_array($route_fn, array_slice($captured, 1)); | |
return true; | |
} | |
} | |
return false; | |
} | |
$get = ['GET' => [ | |
'/a' => function () { echo 'a!'; }, | |
'/b' => function () { echo 'b!'; } | |
]]; | |
$post = ['POST' => [ | |
'/c' => function () { echo 'c!'; } | |
]]; | |
//$_SERVER['REQUEST_METHOD'] = 'GET'; | |
//$_SERVER['REQUEST_URI'] = '/a'; | |
if(!web_app($post + $get, strtoupper($_SERVER['REQUEST_METHOD']), $_SERVER['REQUEST_URI'])) { | |
header('HTTP/1.1 404 Page not found'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment