sealandia-core/router.php

67 lines
1.8 KiB
PHP

<?php
namespace Framework;
class Router{
private $uri;
/**
* Constructor method
* Executed when an instance of the Router class is created
*/
public function __construct(){
$this->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)){
list($controller, $method) = explode('@', $routes[$this->uri]);
$controllerPath = __DIR__ . '/../app/controllers/' . $controller . '.php';
if(file_exists($controllerPath)){
require $controllerPath;
$controller = new $controller();
if(method_exists($controller, $method)){
$controller->$method();
}else{
$this->abort();
}
}else{
$this->abort();
}
}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();
}
}
?>