Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?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
You can’t perform that action at this time.