39 lines
1.1 KiB
PHP
39 lines
1.1 KiB
PHP
<?php
|
|
|
|
namespace App\Core;
|
|
|
|
class Router {
|
|
protected $routes = [];
|
|
|
|
public function add($method, $path, $handler) {
|
|
$path = preg_replace('/\{([a-z]+)\}/', '(?P<\1>[^/]+)', $path);
|
|
$this->routes[] = [
|
|
'method' => strtoupper($method),
|
|
'path' => '#^' . $path . '$#',
|
|
'handler' => $handler
|
|
];
|
|
}
|
|
|
|
public function dispatch($method, $uri) {
|
|
$uri = parse_url($uri, PHP_URL_PATH);
|
|
|
|
foreach ($this->routes as $route) {
|
|
if ($route['method'] === strtoupper($method) && preg_match($route['path'], $uri, $matches)) {
|
|
$handler = $route['handler'];
|
|
$params = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);
|
|
|
|
if (is_array($handler)) {
|
|
[$controllerClass, $methodName] = $handler;
|
|
$controller = new $controllerClass();
|
|
return $controller->$methodName($params);
|
|
}
|
|
|
|
return $handler($params);
|
|
}
|
|
}
|
|
|
|
header("HTTP/1.0 404 Not Found");
|
|
echo "404 Not Found";
|
|
}
|
|
}
|