Files
CRM-IKZ/app/Core/Router.php
T
2026-07-14 08:19:56 +04:00

45 lines
1.1 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Core;
class Router
{
private array $routes = [
'GET' => [],
'POST' => [],
];
public function get(string $path, array $handler): void
{
$this->routes['GET'][] = [$path, $handler];
}
public function post(string $path, array $handler): void
{
$this->routes['POST'][] = [$path, $handler];
}
public function dispatch(string $method, string $uri): void
{
$path = parse_url($uri, PHP_URL_PATH);
foreach ($this->routes[$method] ?? [] as [$route, $handler]) {
$pattern = preg_replace('/\{[a-zA-Z_][a-zA-Z0-9_]*\}/', '([^/]+)', $route);
$pattern = '#^' . $pattern . '$#';
if (preg_match($pattern, $path, $matches)) {
array_shift($matches);
[$class, $action] = $handler;
$controller = new $class();
$controller->$action(...$matches);
return;
}
}
http_response_code(404);
echo '404 Not Found';
}
}