-
-
Save kingkorf/6412160 to your computer and use it in GitHub Desktop.
This file contains 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 | |
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; | |
} | |
?> |
This file contains 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, $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