The front controller

Exercise 4 of 9 in chapter 5 · 150 XP · 5 objectives checked by tests

Topics covered: RouterFront controllerClass constant$_SERVER

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

  1. Create the router ($routeur) with FastRoute\simpleDispatcher(). The function you pass to it receives a RouteCollector (already imported at the top of the file: that's the FastRoute 1.3 API, the installed version). In it, declare the route GET /, with the front page function as its handler.
  2. Ask the router which route matches the request: its method ($_SERVER['REQUEST_METHOD']) and its path (Url::cheminDemande()).
  3. If a route is found, display what its handler ($gestionnaire) returns. The $pages array and the isset() 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.