Léo, the mayor's grandson, has fun typing anything at all in the address bar: /articles/the-mayor-won-the-lottery, /sections/sport… The gazette answers with a blank page, or crashes. A real website answers “this page does not exist”, with the matching HTTP status code, so that browsers and search engines understand it too.
Your mission
-
Next to
rendre(), add a static methodintrouvable(): string(not found) toPage: it sets the 404 status code withhttp_response_code()and returns a page with<main class="lecture">, the heading<h2>Lost in the post</h2>, a word of apology and an<a class="retour">link to the front page. -
When no route matches, show this page.
-
When the route exists but not for this method (a
POSTto the front page), respond 405:$route[0]is thenDispatcher::METHOD_NOT_ALLOWED. A simplehttp_response_code(405);is enough, with or without a page. -
An unknown article or section also responds 404:
- for an unknown article,
Redaction::article()returnsnull; - for a section, replace
Rubrique::from()withRubrique::tryFrom(). Both methods exist on every backed enum, buttryFrom('sport')returnsnullinstead of crashing.
In both cases, test for
nulland return the not-found page:$rubrique = Rubrique::tryFrom($parametres['nom']); if ($rubrique === null) { return Page::introuvable(); }
- for an unknown article,
Reminder
Every HTTP response carries a status code: 200 all is well, 404 not found, 405 method not allowed, 500 server error. http_response_code(404) sets it. It must be called before the page is sent: that is why the handlers return the HTML instead of displaying it, and why echo comes last. Rubrique::from() throws an error for an unknown value, Rubrique::tryFrom() returns null: it's up to you to decide what to do.