sealandia-framework/framework/router.php

68 lines
1.8 KiB
PHP
Raw Normal View History

2024-08-12 17:08:06 +02:00
<?php
2024-08-15 16:10:53 +02:00
namespace sealandia\framework;
2024-08-12 17:08:06 +02:00
class Router{
2024-08-15 16:10:53 +02:00
private $uri;
2024-08-12 17:08:06 +02:00
/**
* Constructor method
* Executed when an instance of the Router class is created
*/
public function __construct(){
2024-08-15 16:10:53 +02:00
$this->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)){
2024-08-15 16:10:53 +02:00
list($controller, $method) = explode('@', $routes[$this->uri]);
$controllerPath = __DIR__ . '/../app/controllers/' . $controller . '.php';
if(file_exists($controllerPath)){
require_once $controllerPath;
$controller = new $controller();
if(method_exists($controller, $method)){
$controller->$method();
}else{
$this->abort();
}
}else{
$this->abort();
}
2024-08-12 17:08:06 +02:00
}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();
}
}
?>