36. PHP: Modern HTTP Router (OOP)
PHPMatching URLs to controllers with parameters.
class Router {
private array $routes = [];
public function add(string $method, string $path, callable $handler): void {
$this->routes[$method][$path] = $handler;
}
public function dispatch(string $method, string $uri): mixed {
return $this->routes[$method][$uri]() ?? http_response_code(404);
}
}
When to use
The foundation of a custom microframework or a simple API without depending on Laravel or Symfony.
Common pitfalls
This simple router doesn't support path parameters (e.g. /users/{id}) — that requires additional pattern-matching logic.