-
-
Save duaneking/6396475 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 | |
// minimal routing | |
function web_app($routes, $verb, $path) { | |
$verb = strtoupper($verb); | |
$path = trim(parse_url($path, PHP_URL_PATH), '/'); | |
foreach ($routes as $route => $func) { | |
@list($req_verb, $req_path) = preg_split('/\s+/', $route, 2); | |
if (!$req_verb || !$req_path) { | |
header('HTTP/1.1 500 METHOD and PATH required for routes', true); | |
exit; | |
} | |
$req_verb = strtoupper($req_verb); | |
$req_path = '@^'.trim($req_path, '/').'$@i'; | |
if ($verb !== $req_verb || !preg_match($req_path, $path, $caps)) | |
continue; | |
call_user_func_array($func, array_slice($caps, 1)); | |
exit; | |
} | |
header('HTTP/1.1 404 Page not found', true); | |
exit; | |
} | |
// sample use | |
$a = ['GET /a' => function () { echo "a!"; }]; | |
$b = ['GET /b' => function () { echo "b!"; }]; | |
$c = ['GET /c' => function () { echo "c!"; }]; | |
web_app( | |
$a + $b + $c, | |
$_SERVER['REQUEST_METHOD'], | |
$_SERVER['REQUEST_URI'] | |
); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment