Zend Framework 2 Routing Basics

An introduction to ZF2 Routing Internals

5,5'
Diego Drigani 04/06/2013 01:47
category: Software Development

Earlier this year, I’ve had the opportunity to speak at the Italian Zfday in Milan, as well as at the Unconf of the PHPDay, the Italian conference on PHP, which is held every year in Verona. In both occasions, I introduced Zend Framework 2 Routing in a talk titled: “Full sail: easy routing with the ZF2” (original title: “Levate l’ancora: Rotte senza problemi con ZF2“). These conferences turned out to be interesting experiences, allowing me to get in touch with the Italian Zend Framework Community. From the positive feedback I have received, I’ve decided to write some blog posts about the topics that were introduced in my talks. So, here it comes this post, the first of a series about zf2 routing.

For starters, what is routing?

The fundamental principle of routing is to match incoming requests reaching an application and decide which fragment of code to execute. That could mean matching either an http request or a console requests (if you are interacting with a Command Line Interface application), and extracting the parameters that determine which snippet of code (IE which controller and then which action) to execute. The other basic principle is to assemble URLs and commands back. That is, from a set of parameters, to build the path of the route. In terms of an example, this means coming up with the /products/view/some_product URL starting from the controller = products, action = view, slug = some_product parameters*.

*I am aware this might not be the best possible example URL, but I hope it gets the message across in simple terms.

Why should we care about routing?

There are different reasons why routing is important. The simplest and most important one is that without routing your application won’t work :-) Even in a working application, though, properly handling routing is important. That’s for different reasons, which can be summarized as follows:

- good URLs are easier to remember, type and share through word of mouth
- they also make it easier for search engines to properly index websites and web applications
- they allow for clean RESTful interfaces to be build
- they improve web application security, because they make it easier for parameters to be properly handled

 

Routing within the Zend Framework 2

Under the Hood

The basic unit of routing is a so called route, which is nothing but a PHP class implementing the following interface:

The RouteInterface includes the  static method factory, which is used to create new routes. Every route is constructed with arguments (usually fetched from specific project/module configuration file). The match method, in turn, accepts a new Request, and determines if the request matches current route. If true, it then returns a RouteMatch object, which is a container object, that includes the route name and most likely all route parameters and values. Last, we also have the assemble method, which takes options and parameters and builds the path of a route (usually an URL).

We will rarely need to worry about implementation details of these methods, though, because the framework will take care of passing the configuration and creating our routes according to our definitions in each module configuration directives (as we’ll shortly see).

Defining new routes

Routes for each module shall be defined within the module configuration file, which can be found in every module’s root folder. The default Zend Framework Skeleton app also has its own Module.php file in /config/modules.config.php:

ZF2 Module Filesystem Layout

 

The section dealing with routing is the one which goes under the router key; routes contains a list of our routes in array form:

In the basic example above, we defined a route named “contact”, of type Literal (all different Route types will be covered in a forthcoming post). Basically we just told the framework to dispatch users requesting the ‘/contact’ URL to the Contact controller, and to have the IndexAction method to be executed.

What about route stacks

The ZF2 router is a collection of routes, based on a priority stack. As it was happening in Zend Framework 1, routes can be added to a route list; the last added route is the one tested first. The same now happens in ZF2; we can now also take advantage of the new priority attribute, though. This means that every route will have a priority value, and highest priorty route will be tested first. I’m sure this will make it easier to keep things organized without needing to worry much about route position within configuration files. This will also make it easier for custom configurations to be used to override third party default configurations.

Every router (there are different types, which we’ll take a look at shortly) implements this interface:

All methods are self-explanatory, so I won’t go in further detail here. This is with the exception of the setRoutes method, which probably deserves some explanation. This method in fact replaces current routes in the stack with the new ones provided as an argument. So, it first removes current routes, then adding the new ones.

Router types

There are different implementations of the aforementioned Router base class:

  • SimpleRouteStack: the most basic implementation, which we can use and extend to make our own router stack class.
  • Http\TreeRouteStack: the most common kind of router, it is used to create a tree of routes to deal with http requests, using a B-tree algorithm to match routes (this ensures that evaluation is efficiently made, as we’ll shortly see).
  • Console\SimpleRouteStack: used in the realm of CLI applications and use to take care of command line arguments. This kind of router will be processed when our application is run from a console terminal window.

Tree Routing

Zend Framework 2 introduces the Tree Routing concept as a big innovation. In fact, it’s very easy to use and its performance is great also: it’s much faster than its ZF1 counterpart. This is for multiple reasons: first off is the fact that the framework doesn’t try to match incoming requests with every single route anymore. This happens because every route can now have an unlimited number of children routes, which aren’t evaluated if parent route didn’t match the request first. Children routes are in fact only instantiated when the router matches or assembles their respective parent routes.

A Tree Route will consist of the following configuration:

  • A base route, known as root route, which describes the base path (first part of an URL, for example);
  • The may_terminate key, which is set to false by default, telling the router whether the route may terminate or not.
  • The child_routes key, an array containing additional routes that stem from the base “route”. Each child route can itself be a Tree Route

Example:

Summary

In this first post about the Zend Framework 2 routing, I’ve introduced what’s a route, what’s routing, how the routing system works in the Zend Framework 2, and how it differs (especially from a performance point of view) from the ZF1 implementation. In my next post, I will be covering different HTTP route types we have at hand. Is there anything else you’d like to know? Just let me know with a comment below.

Posted by Diego Drigani

Follow @drigani on twitter.

Leave a comment

Your email address will not be published. Required fields are marked *

*

*