Over a million developers have joined DZone.

The Wheel: Symfony Routing

DZone 's Guide to

The Wheel: Symfony Routing

· Web Dev Zone ·
Free Resource

Once I started retrofitting a Request object over PHP 4 code, and transforming PHP scripts into objects, a natural need was to associate URLs with the object going to answer a request to them.

You can do this with a simple map:

  '/foo' => 'MyPackage\Foo',
  '/bar' => 'MyPackage\Bar',

but as you scale to many routes of different kinds you may need to introduce additionalo logic on your simple array. The simplest example that calls for a structured solution is that of dynamic routes such as /purchase/42, or even of routing subdomains such as mail.example.com and good.example.com.

Fortunately, there are already open source solutions that address the problem such as Symfony Routing .

Example code

Suppose $routesToClasses is an array like the one in the top of the article:

  '/foo' => 'MyPackage\Foo',
  '/bar' => 'MyPackage\Bar',

To match URLs requested by the client, I have adapter this code straight from documentation in a few minutes:

$routes = new RouteCollection();
foreach ($this->routesToClasses as $routePath => $class) {
  $route = new Route($routePath, array('class' => $class));
  $routes->add($routePath, $route);

$route = rtrim($selectedRoute, '/');
$context = new RequestContext($selectedRoute);
$matcher = new UrlMatcher($this->routes, $context);

try {
  $parameters = $matcher->match($selectedRoute);
  return $parameters;
} catch (ResourceNotFoundException $e) {
  // 404

where $selectedRoute is taken from the Request object or from $_SERVER (in my case REDIRECT_URL, but other keys may apply).

In $parameters, the result of the matching, you find the 'class' key added during initialization, plus any other parameter passed in the same argument to Route. It is also easy enough to provide dynamic URLs, whose variable values are provided as additional parameters:

$route = new Route("/purchase/{id}", array('class' => 'PurchaseController'));
// $parameters will contain not only 'class' but also 'id'

Furthermore, Symfony Routing adds an implicit '_route' key to the matched parameters, containing the $routePath with which the Route was added to the configuration. It is common to rely on this variable to integrate the selection with the rest of an application, for example using the paths as keys in other configuration maps (hidden inside objects).


I appreciate the Routing's job is to associate an URL template to a set of parameters declared by you, enriching them with dynamic (and on occasion implicit such as _route) ones.

It's then your job to decide how to transform this result: parameters can be strings but also controllers, objects in general, or closures that create them for lazy-loading. In my case, the 'class' parameter may be a string that is instantiated via reflection or a closure.

Some of the things Symfony Routing does not do:

  • messing with your Request object and modifying its state, being it the Symfony\HttpFoundation one or your own class.
  • introducing additional dependencies: while there are some suggested installations such as Symfony Config and Symfony Yaml, they are by no means necessary.
  • introducing megabytes of code for a single functionality: we are talking of 70-80 classes, half of which are tests installed through Composer together with the production code.
  • scattering files in dozens of namespaces. All classes are inside the Symfony\Component\Routing namespace and as such even the repository has a good, not Java-like feeling (main/src/org/example/com/routing/Route.java).
  • imposing PHP upgrades: the dependency on PHP 5.3.3 is the bare minimum now that 5.5 is out.


In short, routing is not always a simple job, and can grow complex with the size of your application. It is however a self-contained task that a library can accomplish without taking root all over your application: I wrapped Symfony Routing into a single SymfonyAdapterSet class, implementing a common interface AdapterSet which returns the built object given a URL.

I definitely recommend outsourcing some of the responsibilities of your PHP application to Symfony Routing with respect to doing the matching yourself, with the exception of fixed URLs. What called for the inclusion of the library in the last application I worked on was the need for dynamic ones.


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}