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(){
|
2024-08-13 09:06:11 +02:00
|
|
|
$uri = parse_url($_SERVER['REQUEST_URI'])['path'];
|
2024-08-12 17:08:06 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Method to route the request to the appropriate controller
|
|
|
|
* based on the provided routes
|
|
|
|
*/
|
|
|
|
|
|
|
|
public function routeToController($routes){
|
2024-08-13 09:06:11 +02:00
|
|
|
/**
|
|
|
|
* Check if the requested URI exists in the routes array.
|
|
|
|
* If it exists, require (include and execute) the file corresponding to the route.
|
|
|
|
* If the route doesn't exist, call the abort method to handle the error
|
|
|
|
*/
|
|
|
|
|
2024-08-12 17:08:06 +02:00
|
|
|
if(array_key_exists($this->uri, $routes)){
|
|
|
|
require $routes[$uri];
|
|
|
|
}else{
|
|
|
|
$this->abort();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Method to handle HTTP errors
|
|
|
|
* Default is 404 - Not Found
|
|
|
|
*/
|
|
|
|
|
|
|
|
public function abort($code = 404){
|
2024-08-13 09:06:11 +02:00
|
|
|
/**
|
|
|
|
* Set the HTTP response code to the specified value.
|
|
|
|
* Then include and execute the corresponding error view (e.g., "views/404.php") and Terminate the script execution
|
|
|
|
*/
|
|
|
|
|
2024-08-12 17:08:06 +02:00
|
|
|
http_response_code($code);
|
|
|
|
require "views/{$code}.php";
|
|
|
|
die();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// $routes = [
|
|
|
|
// '/' => 'controllers/index.php',
|
|
|
|
// '/about' => 'controllers/about.php',
|
|
|
|
// '/contact' => 'controllers/contact.php',
|
|
|
|
// ];
|
|
|
|
|
2024-08-15 08:54:44 +02:00
|
|
|
// $router = Router::routeToController($routes);
|
2024-08-12 17:08:06 +02:00
|
|
|
|
|
|
|
?>
|