Skip to content

Instantly share code, notes, and snippets.

@mjburgess
Forked from noodlehaus/web_app.php
Created August 31, 2013 10:15
Show Gist options
  • Save mjburgess/6397377 to your computer and use it in GitHub Desktop.
Save mjburgess/6397377 to your computer and use it in GitHub Desktop.
<?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