40 lines
1.3 KiB
PHP
40 lines
1.3 KiB
PHP
<?php
|
|
|
|
namespace Api\Core;
|
|
|
|
class Router {
|
|
private $routes = [];
|
|
|
|
public function add($method, $path, $handler) {
|
|
$this->routes[] = [
|
|
'method' => $method,
|
|
'path' => $path,
|
|
'handler' => $handler
|
|
];
|
|
}
|
|
|
|
public function handle($method, $uri) {
|
|
// Simple router logic: match path exactly or with :id
|
|
foreach ($this->routes as $route) {
|
|
$pattern = preg_replace('/\/:\w+/', '/(\d+)', $route['path']);
|
|
if ($route['method'] === $method && preg_match('#^' . $pattern . '$#', $uri, $matches)) {
|
|
array_shift($matches); // remove the full match
|
|
return $this->executeHandler($route['handler'], $matches);
|
|
}
|
|
}
|
|
Response::error('Route not found', 404);
|
|
}
|
|
|
|
private function executeHandler($handler, $params) {
|
|
list($controllerName, $methodName) = explode('@', $handler);
|
|
$controllerClass = "Api\\Controllers\\" . $controllerName;
|
|
|
|
if (class_exists($controllerClass)) {
|
|
$controller = new $controllerClass();
|
|
if (method_exists($controller, $methodName)) {
|
|
return call_user_func_array([$controller, $methodName], $params);
|
|
}
|
|
}
|
|
Response::error('Controller or method not found', 500);
|
|
}
|
|
} |