Story 3.2: router php urls

This commit is contained in:
2026-02-04 17:06:28 +01:00
parent d520fe848f
commit 0409bb1327
13 changed files with 253 additions and 34 deletions

38
includes/router.php Normal file
View File

@@ -0,0 +1,38 @@
<?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;
}
}