sealandia-framework/router.php

58 lines
1.4 KiB
PHP

<?php
class Router{
/**
* Constructor method
* Executed when an instance of the Router class is created
*/
public function __construct(){
$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 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
*/
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){
/**
* 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
*/
http_response_code($code);
require "views/{$code}.php";
die();
}
}
// $routes = [
// '/' => 'controllers/index.php',
// '/about' => 'controllers/about.php',
// '/contact' => 'controllers/contact.php',
// ];
// $router = Router::routeToController($routes);
?>