Figure out routing paradigm

This commit is contained in:
Sky Johnson 2024-07-11 20:47:39 -05:00
parent 2683a5b4bb
commit bceb55c4dd
6 changed files with 19 additions and 40 deletions

View File

@ -4,16 +4,16 @@
const SERVER = '../server';
require_once SERVER.'/bootstrap.php';
// check if the server has been installed
if (!installed()) redirect('/install');
// spin up our app container
// spin up our app container and the initial route
$app = new App(DB);
// route the request
// routing follows a simple rule; the first segment of the URI is the
// module, and the module handles the rest
$route = App::$req->uri(0);
$routes = [
'home' => 'HomeModule::home',
];
// redirect depending on installation status
installRedirect($route);
if ($route == '/') return HomeModule::home();
if ($route == '/install') return InstallModule::handle();
// 404
http_response_code(404);
echo '404: ' . $route;

View File

@ -14,18 +14,4 @@ class App
self::$req = new Request(); // the current request
self::$db = new Database($dbPath); // the database
}
public function route(string $uri, array $routes)
{
// check if the module exists
if (isset($routes[$module])) {
// if the module exists, call the module's handle method
$routes[$module]($this);
} else {
// if the module does not exist, render a 404 page
$this->render('404', [
'title' => '404',
]);
}
}
}

View File

@ -15,6 +15,9 @@ const DB = SERVER.'/database/dragon.db';
require_once SERVER.'/library.php'; // include our miscellaneous functions
// define whether we are installed or not
define('INSTALLED', file_exists(SERVER.'/.installed'));
// autoloader map
const MAP = [
// 'Class' => 'path/to/class.php',

View File

@ -1,33 +1,22 @@
<?php // library.php :: Common functions used throughout the program.
/**
* A stopwatch function to return the elapsed time in seconds.
*/
function stopwatch(float $start, int $roundTo = 3): float
{
return round(microtime(true) - $start, $roundTo);
}
/**
* Redirects to a URL.
*/
function redirect(string $url): void
{
header("Location: $url");
exit;
}
/**
* Checks if the server is installed.
*/
function installed(): bool
function installRedirect(string $route)
{
return file_exists(SERVER.'/.installed');
if (!INSTALLED && $route != 'install') redirect('/install');
if (INSTALLED && $route == 'install') redirect('/');
}
/**
* Returns the path to a template.
*/
function template(string $name): string
{
return SERVER."/templates/$name.php";

View File

@ -2,8 +2,9 @@
class HomeModule
{
public static function home(App $app)
public static function home()
{
echo 'Welcome to the home module!';
echo 'Your request is: ' . App::$req->uri(0);
}
}

View File