38 lines
968 B
PHP
38 lines
968 B
PHP
<?php
|
|
/**
|
|
* Router simple pour URLs propres
|
|
*/
|
|
class Router
|
|
{
|
|
private array $routes = [];
|
|
|
|
public function add(string $pattern, string $handler): self
|
|
{
|
|
$regex = preg_replace('/\{(\w+)\}/', '([^/]+)', $pattern);
|
|
$this->routes['#^' . $regex . '$#'] = $handler;
|
|
return $this;
|
|
}
|
|
|
|
public function resolve(string $uri): array
|
|
{
|
|
$path = parse_url($uri, PHP_URL_PATH);
|
|
$path = rtrim($path, '/') ?: '/';
|
|
|
|
foreach ($this->routes as $regex => $handler) {
|
|
if (preg_match($regex, $path, $matches)) {
|
|
array_shift($matches);
|
|
return [$handler, $matches];
|
|
}
|
|
}
|
|
|
|
return ['pages/404.php', []];
|
|
}
|
|
|
|
public function dispatch(): void
|
|
{
|
|
$uri = $_SERVER['REQUEST_URI'] ?? '/';
|
|
[$handler, $params] = $this->resolve($uri);
|
|
$GLOBALS['routeParams'] = $params;
|
|
require __DIR__ . '/../' . $handler;
|
|
}
|
|
} |