News Archive
PhpRiot Newsletter
Your Email Address:

More information

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

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

Before we dive into the code refactoring, I first want to step back and take a look at why you would like to use a framework instead of keeping your plain-old PHP applications as is. Why using a framework is actually a good idea, even for the simplest snippet of code and why creating your framework on top of the Symfony2 components is better than creating a framework from scratch.

I won't talk about the obvious and traditional benefits of using a framework when working on big applications with more than a few developers; the Internet has already plenty of good resources on that topic.

Even if the "application" we wrote yesterday was simple enough, it suffers from a few problems:

A // framework/index.php A $input = $_GET['name']; A printf('Hello %s', $input); A

First, if the name query parameter is not given in the URL query string, you will get a PHP warning; so let's fix it:

A // framework/index.php A $input = isset($_GET['name']) ? $_GET['name'] : 'World'; A printf('Hello %s', $input); A

Then, this application is not secure. Can you believe it? Even this simple snippet of PHP code is vulnerable to one of the most widespread Internet security issue, XSS (Cross-Site Scripting). Here is a more secure version:

A $input = isset($_GET['name']) ? $_GET['name'] : 'World'; A header('Content-Type: text/html; charset=utf-8'); A printf('Hello %s', htmlspecialchars($input, ENT_QUOTES, 'UTF-8')); A

As you might have noticed, securing your code with htmlspecialchars is tedious and error prone. That's one of the reasons why using a template engine like Twig, where auto-escaping is enabled by default, might be a good idea (and explicit escaping is also less painful with the usage of a simple e filter).

As you can see for yourself, the simple code we had written first is not that simple anymore if we want to avoid PHP warnings/notices and make the code more secure.

Beyond security, this code is not even easily testable. Even if there is not much to test, it strikes me that writing unit tests for the simplest possible snippet of PHP code is not natural and feels ugly. Here is a tentative PHPUnit unit test for the above code:

A // framework/test.php A class IndexTest extends \PHPUnit_Framework_TestCase { public function testHello() { $_GET['name'] = 'Fabien

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