A small router maps an HTTP method and exact path to a handler with a safe 404 fallback.
What It Does and When to Use It
Match an exact method and path with a deliberate 404 fallback. Controllers translate HTTP input to operations; domain services implement rules; templates render escaped output.
Requirements, Inputs and Expected Behavior
Confirm the runtime, extension, environment variables, and permissions before running the examples in production. Decode and normalize paths carefully and do not treat unvalidated path strings as filenames.
Example 1: Basic Operation
Match an exact method and path with a deliberate 404 fallback.
<?php
$routes = ['GET /' => static fn () => 'Home', 'GET /health' => static fn () => 'OK'];
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);
$handler = $routes[$method . ' ' . $path] ?? null;
http_response_code($handler ? 200 : 404);
echo $handler ? $handler() : 'Not Found';
Example 2: Behavior and Validation
Restrict dynamic route parameters before using their values.
<?php
$patterns = ['#^/posts/(?P<id>[1-9][0-9]*)$#D'];
$path = '/posts/17';
if (preg_match($patterns[0], $path, $matches)) echo (int)$matches['id'];
Practical Example: Application Use
Return a standards-aware method rejection without falling through to a different handler.
<?php
$allowed = ['GET', 'POST'];
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
if (!in_array($method, $allowed, true)) {
http_response_code(405);
header('Allow: GET, POST');
exit;
}
echo 'Method accepted';
Important Behavior and Edge Cases
The second example highlights: Restrict dynamic route parameters before using their values. The practical example adds: Return a standards-aware method rejection without falling through to a different handler.
Comparison with Related Approaches
| Approach | What changes |
|---|---|
| Controller, service and template responsibilities | Controllers translate HTTP input to operations; domain services implement rules; templates render escaped output. |
| Choosing safely | Treat template names, route parameters and user data as separate trust domains. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Assuming successful execution proves the result is usable | Check the return value, required extension, and observable output of the specific operation. |
| Ignoring runtime and environment differences | Verify PHP version, SAPI, operating system, service access, and permissions before deployment. |
| Skipping operational constraints | Decode and normalize paths carefully and do not treat unvalidated path strings as filenames. |
Key Takeaways
- A small router maps an HTTP method and exact path to a handler with a safe 404 fallback.
- Return a standards-aware method rejection without falling through to a different handler.
- Treat template names, route parameters and user data as separate trust domains.