WizdomWeb/app/Core/Router.php

50 lines
1.5 KiB
PHP

<?php
namespace WizdomNetworks\WizeWeb\Core;
use WizdomNetworks\WizeWeb\Utils\Logger;
use WizdomNetworks\WizeWeb\Utils\ErrorHandler;
class Router
{
protected array $routes = [];
public function add(string $path, string $controller, string $method): void
{
// Normalize the path to remove leading/trailing slashes
$normalizedPath = trim($path, '/');
$this->routes[$normalizedPath] = ['controller' => $controller, 'method' => $method];
Logger::info("Route added: $normalizedPath -> $controller::$method");
}
public function dispatch(string $path): void
{
// Normalize the incoming path to remove leading/trailing slashes
$path = trim($path, '/');
Logger::info("Dispatching path: $path");
if (!isset($this->routes[$path])) {
Logger::error("Route not found: $path");
http_response_code(404);
echo "404 - Page not found";
return;
}
$controllerName = $this->routes[$path]['controller'];
$method = $this->routes[$path]['method'];
Logger::info("Loading controller: $controllerName::$method");
if (!class_exists($controllerName) || !method_exists($controllerName, $method)) {
Logger::error("Controller or method not found: $controllerName::$method");
http_response_code(500);
echo "500 - Internal server error";
return;
}
$controller = new $controllerName();
$controller->$method();
}
}