Before we start with today's topic, let's refactor our current framework just a little to make templates even more readable:
<?php // example.com/web/front.php require_once __DIR__.'/../src/autoload.php'; use Symfony\Component [HttpFoundation\Request;] use Symfony\Component [HttpFoundation\Response;] $request = Request::createFromGlobals(); $map = array( '/hello' => 'hello', '/bye' => 'bye', ); $path = $request->getPathInfo(); if (isset($map[$path])) { ob_start(); extract($request->query->all(), EXTR_SKIP); include sprintf(__DIR__.'/../src/pages/%s.php', $map[$path]); $response = new Response(ob_get_clean()); } else { $response = new Response('Not Found', 404); } $response->send();
As we now extract the request query parameters, simplify the hello.php
template as follows:
<!-- example.com/src/pages/hello.php --> Hello <?php echo htmlspecialchars($name, ENT_QUOTES, 'UTF-8') ?>
Now, we are in good shape to add new features.
One very important aspect of any website is the form of its URLs. Thanks to the URL map, we have decoupled the URL from the code that generates the associated response, but it is not yet flexible enough. For instance, we might want to support dynamic paths to allow embedding data directly into the URL instead of relying on a query string:
# Before /hello?name=Fabien # After /hello/Fabien
To support this feature, we are going to use the Symfony2 Routing component.
As always, add it to composer.json and run the php composer.phar
update command to install it:
{
"require": {
"symfony/class-loader": "2.1.*",
"symfony/http-foundation": "2.1.*",
"symfony/routing": "2.1.*"
}
}
From now on, we are going to use the generated Composer autoloader inste
Truncated by Planet PHP, read more at the original (another 14824 bytes)