PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

Create your own framework... on top of the Symfony2 Components (part 3)

Note: This article was originally published at Planet PHP on 8 January 2012.
Planet PHP

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:

A // framework/bye.php A require_once __DIR__.'/autoload.php'; A use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; A $request = Request::createFromGlobals(); A $response = new Response('Goodbye!'); $response-send(); A

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:

A // framework/init.php A require_once __DIR__.'/autoload.php'; A use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; A $request = Request::createFromGlobals(); $response = new Response(); A

Let's see it in action:

A // framework/index.php A require_once __DIR__.'/init.php'; A $input = $request-get('name', 'World'); A $response-setContent(sprintf('Hello %s', htmlspecialchars($input, ENT_QUOTES, 'UTF-8'))); $response-send(); A

And for the "Goodbye" page:

A // framework/bye.php A require_once __DIR__.'/init.php'; A $response-setContent('Goodbye!'); $response-send(); A

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/goodbye.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:

A // framework/front.php A require_once __DIR__.'/autoload.php'; A use Symfony\Component\HttpFoundation\Request; use Symfon

Truncated by Planet PHP, read more at the original (another 11326 bytes)