The Analogy: The Hotel Switchboard and the Department Directory
A large hotel has a single telephone number the outside world dials. Behind that number sits a switchboard operator with a directory. When a call comes in, the caller states what they want -- "room service", "the spa", "reservations for the Ada Lovelace party" -- and the operator consults the directory to connect the call to the right extension. The outside caller never needs to know the internal extension numbers; they state intent, and the switchboard maps it to a destination. A router is that switchboard: every web request arrives at one entry point, and the router maps the request's method and path to the code that should handle it.
The directory has two columns that both matter: what was asked for, and where it goes. "Room service" and "GET /orders" are the request side; extension 240 and the OrderController::index method are the destination side. Some entries carry a variable -- "connect me to room 512" -- where the room number is part of the request and is passed along to whoever answers. A route with a path parameter like /users/{id} works exactly so: the {id} is captured from the URL and handed to the controller as an argument.
The operator also distinguishes between "no such department" and "that department exists but is closed right now". A caller asking for a department that does not exist gets "no such number"; a caller asking for the spa after hours gets "the spa is closed". These are genuinely different answers. On the web this is the difference between a 404 (no route matches the path at all) and a 405 (the path exists but not for this HTTP method) -- a distinction a careful router preserves because it tells the caller something true about why their request did not connect.
The failure mode is the operator who connects every call to whoever is nearest, or who keeps a directory so tangled that calls land in the wrong department. Callers reach the kitchen when they wanted housekeeping, and nobody can tell why. In routing terms this is the controller that does too much, or route definitions so ad hoc that two paths overlap and the wrong handler answers. The switchboard's value is precise, predictable mapping; the moment the mapping becomes ambiguous or the destination handler sprawls into unrelated work, requests get mishandled and the system becomes impossible to reason about. Clean routing and focused controllers are what keep every request reaching exactly the right place.
Syntax or Core Structure
A router matches an incoming method and path against registered patterns, capturing any path parameters. These illustrations use plain PHP so they run and verify without a framework; Laravel's router is richer but maps requests the same way. Here {id} in a pattern becomes a captured value passed to the handler.
<?php
declare(strict_types=1);
final class Router {
private array $routes = [];
public function add(string $method, string $pattern, callable $handler): void {
$regex = preg_replace('#\{(\w+)\}#', '(?<$1>[^/]+)', $pattern);
$this->routes[] = [$method, "#^$regex$#", $handler];
}
public function dispatch(string $method, string $path): string {
foreach ($this->routes as [$m, $regex, $handler]) {
if ($m === $method && preg_match($regex, $path, $matches)) {
$params = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);
return $handler($params);
}
}
return '404';
}
}
$r = new Router();
$r->add('GET', '/', fn($p) => 'home');
$r->add('GET', '/users/{id}', fn($p) => "user {$p['id']}");
$r->add('GET', '/posts/{slug}/comments/{n}', fn($p) => "post {$p['slug']} comment {$p['n']}");
echo $r->dispatch('GET', '/'), "\n";
echo $r->dispatch('GET', '/users/42'), "\n";
echo $r->dispatch('GET', '/posts/hello/comments/3'), "\n";
echo $r->dispatch('POST', '/users/42'), "\n";
Output:
home
user 42
post hello comment 3
404
The add method converts {id} into a named regex group, so /users/42 captures id as 42 and the handler prints user 42. Multiple parameters work the same way, capturing both slug and n. The POST to /users/42 matches no registered route -- every route here is GET -- so dispatch returns 404. Laravel writes this as Route::get('/users/{id}', [UserController::class, 'show']), but the capture-and-pass mechanism is identical.
Technical Depth: Verbs, Status Codes, and Named Routes
HTTP verbs map to controller actions
RESTful routing pairs each HTTP verb with a conventional controller action. A resource controller gathers these related actions into one class, so the routes for a resource read predictably.
| Verb + path | Action | Purpose |
|---|---|---|
GET /posts | index | List all |
GET /posts/{id} | show | Show one |
POST /posts | store | Create |
PUT /posts/{id} | update | Replace |
DELETE /posts/{id} | destroy | Remove |
<?php
declare(strict_types=1);
final class PostController {
public function index(): string { return 'list posts'; }
public function show(string $id): string { return "show post $id"; }
public function store(): string { return 'create post'; }
public function destroy(string $id): string { return "delete post $id"; }
}
$c = new PostController();
$table = [
'GET /posts' => fn() => $c->index(),
'GET /posts/7' => fn() => $c->show('7'),
'POST /posts' => fn() => $c->store(),
'DELETE /posts/7' => fn() => $c->destroy('7'),
];
foreach (['GET /posts', 'GET /posts/7', 'POST /posts', 'DELETE /posts/7'] as $req) {
echo $req, ' -> ', $table[$req](), "\n";
}
Output:
GET /posts -> list posts
GET /posts/7 -> show post 7
POST /posts -> create post
DELETE /posts/7 -> delete post 7
Each verb-and-path pair routes to a distinct action on the one PostController. Grouping the actions this way is the convention Laravel's Route::resource generates automatically. The controller stays cohesive -- everything about posts in one place -- and the routing table reads as a clear contract of what the resource supports.
404 versus 405
A thorough router distinguishes "no such path" from "path exists, wrong method". Returning 405 (Method Not Allowed) rather than 404 tells the caller the URL is real but the verb is not supported -- useful and correct.
<?php
declare(strict_types=1);
final class Router {
private array $routes = [];
public function add(string $method, string $pattern, callable $h): void {
$regex = preg_replace('#\{(\w+)\}#', '(?<$1>[^/]+)', $pattern);
$this->routes[] = [$method, "#^$regex$#", $h];
}
public function dispatch(string $method, string $path): string {
$pathMatched = false;
foreach ($this->routes as [$m, $regex, $h]) {
if (preg_match($regex, $path, $mt)) {
$pathMatched = true;
if ($m === $method) {
$params = array_filter($mt, 'is_string', ARRAY_FILTER_USE_KEY);
return $h($params);
}
}
}
return $pathMatched ? '405 Method Not Allowed' : '404 Not Found';
}
}
$r = new Router();
$r->add('GET', '/orders/{id}', fn($p) => "order {$p['id']}");
echo $r->dispatch('GET', '/orders/9'), "\n";
echo $r->dispatch('POST', '/orders/9'), "\n";
echo $r->dispatch('GET', '/nope'), "\n";
Output:
order 9
405 Method Not Allowed
404 Not Found
The GET /orders/9 matches and runs. The POST /orders/9 matches the path but not the method, so the router remembers the path matched and returns 405. The GET /nope matches nothing, so it returns 404. This mirrors what a real framework does: the status code is part of the honest answer, and conflating the two loses information the client can act on.
Route groups and shared prefixes
Related routes usually share a prefix -- everything under /admin, say. Declaring the prefix once as a group, rather than repeating it on every line, keeps the routing table concise and makes it obvious which routes belong together.
<?php
declare(strict_types=1);
final class Router {
private array $routes = [];
private string $prefix = '';
public function group(string $prefix, callable $define): void {
$previous = $this->prefix;
$this->prefix = $previous . $prefix;
$define($this);
$this->prefix = $previous;
}
public function get(string $path, callable $h): void {
$this->routes['GET ' . $this->prefix . $path] = $h;
}
public function dispatch(string $method, string $path): string {
$h = $this->routes["$method $path"] ?? null;
return $h ? $h() : '404';
}
}
$r = new Router();
$r->get('/', fn() => 'public home');
$r->group('/admin', function (Router $r) {
$r->get('/users', fn() => 'admin users');
$r->get('/settings', fn() => 'admin settings');
});
echo $r->dispatch('GET', '/'), "\n";
echo $r->dispatch('GET', '/admin/users'), "\n";
echo $r->dispatch('GET', '/admin/settings'), "\n";
echo $r->dispatch('GET', '/admin'), "\n";
Output:
public home
admin users
admin settings
404
The group method prepends /admin while the callback registers its routes, then restores the previous prefix on exit, so /admin/users and /admin/settings are registered without repeating the prefix. The bare /admin matches nothing because no route was registered at exactly that path. Laravel's Route::prefix('admin')->group(...) does this and also attaches shared middleware to the group, the natural place to require authentication for every admin route at once.
Real World Example: Named Routes and URL Generation
A key routing feature is naming routes so URLs are generated from the name rather than hard-coded throughout the codebase. If a path changes, only the route definition changes; every link built from the name updates automatically. Here the router both dispatches and generates URLs from named patterns.
<?php
declare(strict_types=1);
final class Router {
private array $routes = [];
public function add(string $name, string $method, string $pattern, callable $h): void {
$this->routes[$name] = [$method, $pattern, $h];
}
public function dispatch(string $method, string $path): string {
foreach ($this->routes as [$m, $pattern, $h]) {
$regex = preg_replace('#\{(\w+)\}#', '(?<$1>[^/]+)', $pattern);
if ($m === $method && preg_match("#^$regex$#", $path, $mt)) {
return $h(array_filter($mt, 'is_string', ARRAY_FILTER_USE_KEY));
}
}
return '404';
}
public function url(string $name, array $params = []): string {
[, $pattern] = $this->routes[$name] ?? throw new RuntimeException("no route: $name");
return preg_replace_callback('#\{(\w+)\}#', function ($m) use ($params) {
return (string) ($params[$m[1]] ?? throw new RuntimeException("missing param: {$m[1]}"));
}, $pattern);
}
}
$r = new Router();
$r->add('user.show', 'GET', '/users/{id}', fn($p) => "profile of {$p['id']}");
$r->add('home', 'GET', '/', fn($p) => 'home');
echo $r->dispatch('GET', '/users/7'), "\n";
echo 'url: ', $r->url('user.show', ['id' => 7]), "\n";
echo 'url: ', $r->url('home'), "\n";
try {
$r->url('user.show');
} catch (RuntimeException $e) {
echo 'error: ', $e->getMessage(), "\n";
}
Output:
profile of 7
url: /users/7
url: /
error: missing param: id
Routes are keyed by name -- user.show, home -- so url('user.show', ['id' => 7]) rebuilds the path /users/7 by filling the {id} placeholder. A parameterless route like home generates / directly. Asking for a URL without a required parameter throws missing param: id, catching a broken link at generation time rather than shipping a malformed URL. This is precisely Laravel's route('user.show', ['id' => 7]) helper in miniature.
The design flaw is that URL generation and dispatch use two independent regex passes over the same pattern, and nothing guarantees they stay consistent as the pattern grows more complex. The dispatch side treats every {param} as [^/]+, but a real router often needs constraints -- {id} should match only digits, {slug} only word characters -- and the url method here does no validation of the values it substitutes, so url('user.show', ['id' => 'a/b']) would happily produce /users/a/b, a URL that the dispatcher would then fail to match back to this route. Generation and matching are meant to be inverses, and here they can silently disagree: a URL the generator produces is not guaranteed to route back to the same handler. A robust router shares one constraint definition between matching and generation, and validates substituted values against it, so a generated URL always round-trips. Keeping two hand-written regexes in step by convention alone is exactly the kind of subtle inconsistency that a framework's unified route definition exists to eliminate.
Common Mistakes
- Fat controllers. A controller action that queries, calculates, formats, and emails does too much. Keep actions thin -- coordinate and delegate to services.
- Not constraining route parameters. Letting
{id}match anything routes/users/abcto a handler expecting a number. Constrain parameters so only valid values match.
- Conflating 404 and 405. Returning 404 when the path exists but the method is wrong hides useful information. Distinguish "no such path" from "wrong method".
- Hard-coding URLs. Scattering literal paths through views and code means a path change breaks links everywhere. Generate URLs from named routes.
- Overlapping route patterns. Two routes that both match a path make dispatch order-dependent and fragile. Keep patterns unambiguous, and order specific before general.
- Ignoring the HTTP method. Handling
GETandPOSTin one action by inspecting the method by hand reinvents routing. Register separate routes per verb.
- Putting logic in route definitions. A route file full of closures with real logic becomes untestable. Point routes at controller methods instead.
- Forgetting a catch-all or fallback. With no fallback, unmatched routes may error confusingly. Define a clear 404 handler.
- Trusting route parameters as safe. A captured
{id}is still user input. Validate and bind it before using it in a query, exactly as with any other input.
Best Practices
- Keep controllers thin: an action should coordinate the request and hand real work to services and models.
- Group a resource's actions into one controller and register its routes by convention, so the routing table reads as a clear contract.
- Constrain route parameters to their expected shape, so only valid URLs reach a handler.
- Return the honest status code -- 404 for an unknown path, 405 for a known path with an unsupported method.
- Name your routes and generate URLs from those names, so a path change updates every link automatically.
- Keep route patterns unambiguous and ordered from specific to general, so dispatch is predictable.
- Treat every captured parameter as untrusted input, validating and binding it before use.
- Point routes at controller methods rather than embedding logic in route closures, keeping the routing layer thin and testable.
Practice Exercises
- Build a router that converts
{param}patterns to named regex groups, register three routes including one with two parameters, and show the captured values passed to each handler.
- Add 404-versus-405 handling: dispatch a request to a known path with the wrong method and confirm it returns 405, while an unknown path returns 404.
- Create a resource-style controller with
index,show,store, anddestroy, wire each to the conventional verb-and-path, and demonstrate all four routing correctly.
- Add named routes and a
url(name, params)generator, and show that generating a URL for a route with a missing required parameter throws a clear error.