71 lines
2.3 KiB
PHP
71 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace WizdomNetworks\WizeWeb\Core;
|
|
|
|
use WizdomNetworks\WizeWeb\Utils\Logger;
|
|
use WizdomNetworks\WizeWeb\Utils\ErrorHandler;
|
|
|
|
/**
|
|
* Router Class
|
|
*
|
|
* Handles application routing by mapping URL paths to controller methods.
|
|
* Ensures all requests are routed through controllers and logs dispatch details.
|
|
*/
|
|
class Router
|
|
{
|
|
private array $routes = [];
|
|
|
|
/**
|
|
* Registers a new route.
|
|
*
|
|
* @param string $path The URL path.
|
|
* @param string $controller The fully qualified controller class name.
|
|
* @param string $method The method within the controller.
|
|
*/
|
|
public function add(string $path, string $controller, string $method): void
|
|
{
|
|
Logger::debug("Registering route: $path -> $controller::$method");
|
|
$this->routes[trim($path, '/')] = [$controller, $method];
|
|
}
|
|
|
|
/**
|
|
* Dispatches the request to the appropriate controller and method.
|
|
*
|
|
* @param string $path The requested URL path.
|
|
*/
|
|
public function dispatch($path)
|
|
{
|
|
$path = trim($path, '/');
|
|
Logger::debug("Dispatching path: $path");
|
|
|
|
if (isset($this->routes[$path])) {
|
|
[$controllerName, $method] = $this->routes[$path];
|
|
Logger::debug("Loading controller: $controllerName::$method");
|
|
|
|
try {
|
|
if (class_exists($controllerName)) {
|
|
$controller = new $controllerName();
|
|
|
|
if (method_exists($controller, $method)) {
|
|
Logger::info("Successfully dispatched: $controllerName::$method");
|
|
$controller->$method();
|
|
} else {
|
|
Logger::error("Method not found: $controllerName::$method");
|
|
throw new \Exception("Method $method not found in $controllerName");
|
|
}
|
|
} else {
|
|
Logger::error("Controller not found: $controllerName");
|
|
throw new \Exception("Controller $controllerName not found.");
|
|
}
|
|
} catch (\Throwable $e) {
|
|
ErrorHandler::exception($e);
|
|
Logger::error("Router dispatch error: " . $e->getMessage());
|
|
echo "500 Internal Server Error";
|
|
}
|
|
} else {
|
|
Logger::error("Route not found: $path");
|
|
echo "404 Not Found";
|
|
}
|
|
}
|
|
}
|