sealandia-framework/router.php

54 lines
1.5 KiB
PHP
Raw Normal View History

2024-08-12 17:08:06 +02:00
<?php
class Router{
/**
* Constructor method
* Executed when an instance of the Router class is created
*/
public function __construct(){
/* Parse the URL from the request and extract the path part (e.g., "/home" from "http://example.com/home") */
$uri = parse_url($_SERVER['REQUEST_URI'])['path'];
}
/**
* Method to route the request to the appropriate controller
* based on the provided routes
*/
public function routeToController($routes){
// Check if the requested URI exists in the routes array
if(array_key_exists($this->uri, $routes)){
// If it exists, require (include and execute) the file corresponding to the route
require $routes[$uri];
}else{
// If the route doesn't exist, call the abort method to handle the error
$this->abort();
}
}
/**
* Method to handle HTTP errors
* Default is 404 - Not Found
*/
public function abort($code = 404){
// Set the HTTP response code to the specified value
http_response_code($code);
// Include and execute the corresponding error view (e.g., "views/404.php")
require "views/{$code}.php";
// Terminate the script execution
die();
}
}
// $routes = [
// '/' => 'controllers/index.php',
// '/about' => 'controllers/about.php',
// '/contact' => 'controllers/contact.php',
// ];
// $router = (new Router)->routeToController($routes);
?>