✨ Story 3.2: router php urls
This commit is contained in:
38
includes/router.php
Normal file
38
includes/router.php
Normal 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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user