Skip to content

Instantly share code, notes, and snippets.

@noodlehaus
Last active December 15, 2017 06:39
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save noodlehaus/6395996 to your computer and use it in GitHub Desktop.
Save noodlehaus/6395996 to your computer and use it in GitHub Desktop.
bare bones routing function for PHP.
<?php
// minimal routing
function web_app($routes, $req_verb, $req_path) {
$req_verb = strtoupper($req_verb);
$req_path = trim(parse_url($req_path, PHP_URL_PATH), '/');
$found = false;
if (isset($routes[$req_verb])) {
foreach ($routes[$req_verb] as $path => $action) {
$path = '@^'.trim($path, '/').'$@';
if (!preg_match($path, $req_path, $capture))
continue;
$found = true;
call_user_func_array($action, array_slice($capture, 1));
}
}
if (!$found)
throw new Exception('Resource not found');
}
// sample calls
// sample resource
class MyObject {
public function methodName() {
echo "d!";
}
}
// sample function
function b_function() {
echo "b!";
}
// sample routes
$routes1 = ['GET' => [
'/a' => function () { echo "a!"; },
'/b' => 'b_function'
]];
// more routes
$routes2 = [
'GET' => [
'/c/([0-9]+)' => function ($id) { echo "{$id}!"; },
'/d' => array(new MyObject, 'methodName')
],
'POST' => [
'/e' => function () { echo "e!"; },
'/f' => function () { echo "f!"; }
]
];
// serve routes
try {
web_app(
array_merge_recursive($routes1, $routes2),
$_SERVER['REQUEST_METHOD'],
$_SERVER['REQUEST_URI']
);
} catch (Exception $e) {
header('HTTP/1.1 404 Page not found', true);
exit;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment