Your $pages array works, but Madame Lou is already looking further ahead: /articles/the-pumpkin-festival, /articles/the-mayors-cat-is-missing… One line per article, by hand, would never end. The router you installed earlier, FastRoute, can recognize whole families of addresses. For now, it will simply replace your array, without changing anything on the front page.
Your mission
- Create the router (
$routeur) withFastRoute\simpleDispatcher(). The function you pass to it receives aRouteCollector(already imported at the top of the file: that's the FastRoute 1.3 API, the installed version). In it, declare the routeGET /, with the front page function as its handler. - Ask the router which route matches the request: its method (
$_SERVER['REQUEST_METHOD']) and its path (Url::cheminDemande()). - If a route is found, display what its handler (
$gestionnaire) returns. The$pagesarray and theisset()go away.
From your array to the router
Each line of your homemade router has its counterpart. Before:
$pages = ['/' => $une]; $chemin = Url::cheminDemande(); if (isset($pages[$chemin])) { echo $pages[$chemin](); }
After:
$routeur = FastRoute\simpleDispatcher(function (RouteCollector $routes) { $routes->get('/', function (): string { // … the body of $une, unchanged … }); }); $route = $routeur->dispatch($_SERVER['REQUEST_METHOD'], Url::cheminDemande()); if ($route[0] === Dispatcher::FOUND) { $gestionnaire = $route[1]; echo $gestionnaire($route[2]); }
FastRoute\simpleDispatcher() is a function that lives in the FastRoute namespace: you call it by its full name, without use.
dispatch() returns an array: at [0], the result (Dispatcher::FOUND if a route matches), at [1] the handler, at [2] the variable parts of the address, empty for the front page. The router also takes the method into account: GET to read a page, POST to send a form.
Reminder
Dispatcher::FOUND is a class constant: a fixed value, stored in the Dispatcher class, that you read with ::. public/index.php receives every address of the site and lets the router choose the page: that's the front controller.