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

Fabien Potencier

January 09, 2012

This article is part of a series of articles that explains how to create a framework with the Symfony2 Components: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12.

Before we start with today's topic, let's refactor our current framework just a little to make templates even more readable:

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])) {
    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);

As we now extract the request query parameters, simplify the hello.php template as follows:

<!-- -->
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
# After

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 instead of our own autoload.php. Remove the autoload.php file and replace its reference in front.php:

require_once __DIR__.'/../vendor/.composer/autoload.php';
// ...

Instead of an array for the URL map, the Routing component relies on a RouteCollection instance:

use Symfony\Component\Routing\RouteCollection;
$routes = new RouteCollection();

Let's add a route that describe the /hello/SOMETHING URL and add another one for the simple /bye one:

use Symfony\Component\Routing\Route;
$routes->add('hello', new Route('/hello/{name}', array('name' => 'World')));
$routes->add('bye', new Route('/bye'));

Each entry in the collection is defined by a name (hello) and a Route instance, which is defined by a route pattern (/hello/{name}) and an array of default values for route attributes (array('name' => 'World')).

Read the official documentation -- available soon -- for the Routing component to learn more about its many features like URL generation, attribute requirements, HTTP method enforcements, loaders for YAML or XML files, dumpers to PHP or Apache rewrite rules for enhanced performance, and much more.

Based on the information stored in the RouteCollection instance, a UrlMatcher instance can match URL paths:

use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Matcher\UrlMatcher;
$context = new RequestContext();
$matcher = new UrlMatcher($routes, $context);
$attributes = $matcher->match($request->getPathInfo());

The match() method takes a request path and returns an array of attributes (notice that the matched route is automatically stored under the special _route attribute):

array (
  '_route' => 'bye',
array (
  'name' => 'Fabien',
  '_route' => 'hello',
array (
  'name' => 'World',
  '_route' => 'hello',

Even if we don't strictly need the request context in our examples, it is used in real-world applications to enforce method requirements and more.

The URL matcher throws an exception when none of the routes match:

// throws a Symfony\Component\Routing\Exception\ResourceNotFoundException

With this knowledge in mind, let's write the new version of our framework:

require_once __DIR__.'/../vendor/.composer/autoload.php';
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing;
$request = Request::createFromGlobals();
$routes = include __DIR__.'/../src/app.php';
$context = new Routing\RequestContext();
$matcher = new Routing\Matcher\UrlMatcher($routes, $context);
try {
    extract($matcher->match($request->getPathInfo()), EXTR_SKIP);
    include sprintf(__DIR__.'/../src/pages/%s.php', $_route);
    $response = new Response(ob_get_clean());
} catch (Routing\Exception\ResourceNotFoundException $e) {
    $response = new Response('Not Found', 404);
} catch (Exception $e) {
    $response = new Response('An error occurred', 500);

There are a few new things in the code:

  • Route names are used for template names;

  • 500 errors are now managed correctly;

  • Request attributes are extracted to keep our templates simple:

    <!-- -->
    Hello <?php echo htmlspecialchars($name, ENT_QUOTES, 'UTF-8') ?>
  • Routes configuration has been moved to its own file:

    use Symfony\Component\Routing;
    $routes = new Routing\RouteCollection();
    $routes->add('hello', new Routing\Route('/hello/{name}', array('name' => 'World')));
    $routes->add('bye', new Routing\Route('/bye'));
    return $routes;

    We now have a clear separation between the configuration (everything specific to our application in app.php) and the framework (the generic code that powers our application in front.php).

With less than 30 lines of code, we have a new framework, more powerful and more flexible than the previous one. Enjoy!

Using the Routing component has one big additional benefit: the ability to generate URLs based on Route definitions. When using both URL matching and URL generation in your code, changing the URL patterns should have no other impact. Want to know how to use the generator? Insanely easy:

use Symfony\Component\Routing;
$generator = new Routing\Generator\UrlGenerator($routes, $context);
echo $generator->generate('hello', array('name' => 'Fabien'));
// outputs /hello/Fabien

The code should be self-explanatory; and thanks to the context, you can even generate absolute URLs:

echo $generator->generate('hello', array('name' => 'Fabien'), true);
// outputs something like

Concerned about performance? Based on your route definitions, create a highly optimized URL matcher class that can replace the default UrlMatcher:

$dumper = new Routing\Matcher\Dumper\PhpMatcherDumper($routes);
echo $dumper->dump();

Want even more performance? Dump your routes as a set of Apache rewrite rules:

$dumper = new Routing\Matcher\Dumper\ApacheMatcherDumper($routes);
echo $dumper->dump();


gravatar Benjamin Eberlei  — January 09, 2012 09:57   #1
There are two missing single quotes in the 3rd and 4th last code boxes near 'Fabien
gravatar Fabien Potencier  — January 09, 2012 10:01   #2
Good catch Benjamin. Fixed now.
gravatar Loïc Chardonnet  — January 09, 2012 10:27   #3
As usual, great article! Routes are definitely an essential asset for frameworks!
The generator is the ultimate "HtmlLinkHelper" :D .

But why switching to composer's autoloader? Just to remove the "autoload.php" file and make the framework lighter?
Anyway, since autoloading is explained (first article), I suppose it doesn't matter whose class is used...
gravatar Fabien Potencier  — January 09, 2012 10:53   #4
@Loïc: I have switched to the Composer autoloader as it updates itself automatically each time we add a new dependency. As the Symfony2 ClassLoader has already been explained, it makes the articles shorter.
gravatar Amitay Horwitz  — January 09, 2012 10:59   #5
Aren't you suppose to return $routes at the end of src/app.php?
gravatar Matt Robinson  — January 09, 2012 11:17   #6
In your initial example, the extract() call has the ability to override the global scope, specifically $map and $path. In the examples above, this doesn't look too serious - loading the wrong template - but it could be worse if someone decided to add more logic after the response creation and before sending.

The easiest way to fix it is to prevent extract() from overwriting existing variables by passing a second argument of EXTR_SKIP. The /best/ way is to use Symfony2 ;)
gravatar Matt Robinson  — January 09, 2012 11:27   #7
(… and then I found that two of my own projects had the same potential flaw. D'oh!)
gravatar Fabien Potencier  — January 09, 2012 11:42   #8
@Amitay: I have added the missing $routes.
@Matt: Fixed now.
gravatar Jay Williams  — January 09, 2012 16:35   #9
Thank you, Fabien, for writing these articles. It's definitely helped my understanding of how the Symfony components operate outside of the full Symfony stack.
gravatar Xavier Lacot  — January 09, 2012 18:41   #10
+1 with Jay. A great serie of articles, and a very interesting content that every Sf2 developer should read. Thanks a lot!
gravatar Berny Cantos  — January 09, 2012 20:17   #11
I'm learning a lot about Symfony2 and it's components with these articles! So good that even a newbie would understand how it works underneath. Great! Thanks Fabien!
gravatar chris yue  — January 11, 2012 04:36   #12
Greate series indeed! Can I translate it into Chinese to all chinese symfony fans? In fact I've already translated the part 1:
gravatar Jurijs Kobecs  — January 22, 2012 20:17   #13

I got these 'rules' for rewrite engine, but they didn't work for me..

# skip "real" requests
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule .* - [QSA,L]

# hello
RewriteCond %{REQUEST_URI} ^/hello(?:/([^/]+?))?$
RewriteRule .* app.php [QSA,L,E=_ROUTING__route:hello,E=_ROUTING_name:%1,E=_ROUTING_name:World]

# bye
RewriteCond %{REQUEST_URI} ^/bye$
RewriteRule .* app.php [QSA,L,E=_ROUTING__route:bye]