A plain PHP router matches HTTP methods and paths to handlers for clean navigation.
What It Does
A plain PHP router matches HTTP methods and paths to handlers for clean navigation. The following examples distinguish a normal use case, a boundary case and a practical application.
Requirements and Compatibility
PHP 8.x and a local test environment. Apply input validation, correct error handling and the requirements of any optional libraries.
The code focuses on the core concept. Production implementation may also need routes, validation, persistence, authorization or deployment tooling.
Example 1: Basic Behavior
Understand the primary operation and its inputs.
<?php
$routes = ['GET /items' => fn () => 'list', 'POST /items' => fn () => 'create'];
$key = 'GET /items';
echo isset($routes[$key]) ? $routes[$key]() : '404';
Example 2: Another Case
Check failure behavior or a different execution path.
<?php
$path = parse_url('/items/17?view=short', PHP_URL_PATH);
if (preg_match('~^/items/(?P<id>\d+)$~D', $path, $m)) echo (int) $m['id'];
Practical Example: Putting It to Use
Apply the behavior in a small, controlled scenario.
<?php
function controller(array $request): array { return ['status' => 200, 'body' => ['method' => $request['method']]]; }
echo json_encode(controller(['method' => 'GET']), JSON_THROW_ON_ERROR); // Render the response separately
Important Behavior and Edge Cases
Parsing route parameters does not authenticate or authorize them; normalize URL paths carefully.
Comparison with Related Functions or Approaches
| Option | What it means in practice |
|---|---|
| Building Basic URL Routing in PHP | A plain PHP router matches HTTP methods and paths to handlers for clean navigation. |
| Related approach | A front controller dispatches all requests through one entry point. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the important boundary for Building Basic URL Routing in PHP | Parsing route parameters does not authenticate or authorize them; normalize URL paths carefully. |
| Assuming a related mechanism has the same behavior | A front controller dispatches all requests through one entry point. |
Key Takeaways
- A plain PHP router matches HTTP methods and paths to handlers for clean navigation.
- Parsing route parameters does not authenticate or authorize them; normalize URL paths carefully.
- A front controller dispatches all requests through one entry point.
Before adapting these examples, verify the return values, test the failure paths and confirm that your application meets its security and environment requirements.