Madame Lou has big plans: one page per article, one page per section, a form for classified ads… All these addresses will land in the same public/index.php. So she needs a way to choose what to display depending on the requested address. Before calling in a tool to the rescue, let's build it by hand, with anonymous functions.
Your mission
-
Put the building of the front page inside an anonymous function, stored in a variable
$une(front page). It returns the page withreturn Page::rendre(...), instead of displaying it:$une = function (): string { // … $html as before … return Page::rendre('The Saint-Glinglin Gazette', $html . '</main>'); };
-
Declare the array of the site's pages, which maps an address to the function that builds it:
$pages = ['/' => $une];. -
Get the requested address with
Url::cheminDemande()(requested path). If it is in the array (isset()), call its function and display what it returns.
The front page doesn't change. An unknown address, like /nowhere, shows a blank page for now: the error page will come later.
Why Url::cheminDemande()?
The requested address is in $_SERVER['REQUEST_URI'], but not on its own. In the editor's preview, the gazette is served under a prefix (/preview/…), and a link shared on LinkedIn adds ?utm_source=linkedin at the end. Url::cheminDemande() removes both and keeps only the path: /.
Reminder
An anonymous function is a function without a name, which you store in a variable like any other value. You call it with parentheses after the variable: $une(). Since it's a value, it can also go in an array: $pages['/']() calls the function for the address /. isset() checks that a key exists in an array before you use it. This array of addresses and functions is already a router, a homemade one.