Up until now, our application is simplistic as there is only one page. To spice things up a little bit, let's go crazy and add another page that says goodbye:
<?php // framework/bye.php require_once __DIR__.'/autoload.php'; use Symfony\Component [HttpFoundation\Request;] use Symfony\Component [HttpFoundation\Response;] $request = Request::createFromGlobals(); $response = new Response('Goodbye!'); $response->send();
As you can see for yourself, much of the code is exactly the same as the one we have written for the first page. Let's extract the common code that we can share between all our pages. Code sharing sounds like a good plan to create our first "real" framework!
The PHP way of doing the refactoring would probably be the creation of an include file:
<?php // framework/init.php require_once __DIR__.'/autoload.php'; use Symfony\Component [HttpFoundation\Request;] use Symfony\Component [HttpFoundation\Response;] $request = Request::createFromGlobals(); $response = new Response();
Let's see it in action:
<?php
// framework/index.php
require_once __DIR__.'/init.php';
$input = $request->get('name', 'World');
$response->setContent(sprintf('Hello %s', htmlspecialchars($input, ENT_QUOTES, 'UTF-8')));
$response->send();
And for the "Goodbye" page:
<?php
// framework/bye.php
require_once __DIR__.'/init.php';
$response->setContent('Goodbye!');
$response->send();
We have indeed moved most of the shared code into a central place, but it does
not feel like a good abstraction, doesn't it? First, we still have the
send() method in all pages, then our pages does not look like templates,
and we are still not able to test this code properly.
Moreover, adding a new page means that we need to create a new PHP script,
which name is exposed to the end user via the URL
(http://example.com/bye.php): there is a direct mapping between the PHP
script name and the client URL. This is because the dispatching of the request
is done by the web server directly. It might be a good idea to move this
dispatching to our code for better flexibility. This can be easily achieved by
routing all client requests to a single PHP script.
Exposing a single PHP script to the end user is a design pattern called the "front controller".
Such a script might look like the following:
<?php // framework/front.php require_once __DIR__.'/autoload.php'; use Symfony\Component [HttpFoundation\Request;] use Symfony\Co
Truncated by Planet PHP, read more at the original (another 11323 bytes)