Skip to content

Instantly share code, notes, and snippets.

@kingkorf
Forked from noodlehaus/web_app.php
Created September 2, 2013 12:05
Show Gist options
  • Save kingkorf/6412160 to your computer and use it in GitHub Desktop.
Save kingkorf/6412160 to your computer and use it in GitHub Desktop.
<?php
require './web_app.php';
// 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;
}
?>
<?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');
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment