Skip to content

Instantly share code, notes, and snippets.

@agarciadelrio
Last active June 30, 2022 09:31
Show Gist options
  • Save agarciadelrio/d9bd93cda7ecbc7c2b1a9814877fcbe1 to your computer and use it in GitHub Desktop.
Save agarciadelrio/d9bd93cda7ecbc7c2b1a9814877fcbe1 to your computer and use it in GitHub Desktop.
PHP Simple router
<?php
$ROUTES = [
'GET' => [
'home' => 'Home::index',
'ping' => 'Session::getPing',
],
'POST' => [
'ping' => 'Session::postPing',
]
];
$parse_url = parse_url( $_SERVER['REQUEST_URI'] );
if($parse_url['path']==='/') { $parse_url['path']='/home'; }
$url = $parse_url;
$url['path'] = rtrim( $url['path'], '/' );
if($url['path']=='') { $url['path']='/home'; }
if(isset($url['query'])) {
parse_str( $url['query'], $url['params'] );
}
$url['crumbs'] = explode('/', trim($url['path'],'/'));
$method = strtoupper($_SERVER['REQUEST_METHOD']);
$url['method'] = $method;
$_action = $url['crumbs'][0];
if(isset($ROUTES[$url['method']]) && isset($ROUTES[$url['method']][$_action])) {
$action = $ROUTES[$url['method']][$_action];
if($action) {
$p = explode('::', $action);
$controller_file_name = __DIR__ . "lib/controller/{$p[0]}Controller.php";
if(file_exists($controller_file_name)) {
require_once($controller_file_name);
$response = call_user_func($action, $url);
echo $response;
} else {
throw new Exception("Not Implemented", 501);
}
} else {
throw new Exception("Method Not Allowed", 405);
}
} else {
throw new Exception("Not Found", 404);
}
die;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment