php · level 3 · unit 6 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A reads the request and picks the code that answers it.
Every visit to a web app arrives as a request: a method such as GET or POST, plus a path such as /pets. Frameworks keep a list of routes, each linking a method and a path to a , a closure that builds the answer.
The router's job is small. It reads $_SERVER["REQUEST_METHOD"] and $_SERVER["REQUEST_URI"], looks up the matching and calls its handler. No match? It answers 404, the web's code for not found. Here, the top three lines pretend the request.
<?php
$_SERVER["REQUEST_METHOD"] = "GET";
$_SERVER["REQUEST_URI"] = "/pets";
$routes = [
"GET /" => fn() => "Welcome to the pet shop!",
"GET /pets" => fn() => "Rex, Tom and Bella",
"POST /pets" => fn() => "Pet added",
];
$key = $_SERVER["REQUEST_METHOD"] . " " . $_SERVER["REQUEST_URI"];
$handler = $routes[$key] ?? fn() => "404 Not Found";
echo $handler() . "\n"; Real frameworks add patterns like /pets/{id}, but underneath they do exactly this lookup.
guess first
A Router class gets a POST. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
class Router {
private array $routes = [];
public function get(string $path, callable $handler): void {
$this->routes["GET $path"] = $handler;
}
public function dispatch(string $method, string $path): string {
$handler = $this->routes["$method $path"] ?? fn() => "404 Not Found";
return $handler();
}
}
$router = new Router();
$router->get("/about", fn() => "About us");
echo $router->dispatch("POST", "/about") . "\n";
your turn
Your turn. Add a page to the café's site.
Type a new path, like /contact, in both path blanks, then the words its page should say. Line 3 pretends a visit to that path.
fix it
Adding to the basket says not found. Fix it.
- The route exists, so the key must be wrong. Work out exactly what string line 8 builds.
- Line 8 makes "POST/basket", but the route's key is "POST /basket", with a space in the middle.
- On line 8, join a space between the method and the path, as in
. " " ., then run it.
nailed it
you built the heart of a framework. :D
- A route links a method and a path to a handler.
- The router builds a key from the request and calls the match.
- No matching route means a 404 Not Found answer.
new words in your collection
- route
- handler
- router
This lesson isn’t saved. A free account remembers every lesson you finish.