ZF2 Routing Explained

When a site user enters a URL in a web browser, the request is finally dispatched to controller’s action. ZF2-based application maps page URLs to controllers and their actions. This mapping is accomplished with the help of routing. Routing is implemented as a part of Zend\Mvc component.

URL Structure

To better understand routing, we first need to look at the URL structure. A typical URL from an HTTP request consists of segments. The segments are URL parts delimited by slash characters (‘/’): there are scheme, host name, path and query segments.

For example, let’s look at the URL http://site1.yourserver.com/path/to/page?query=Search

This URL begins with a scheme segment (the scheme typically looks like http or https). Then, the host name segment follows which is the domain name of your web server (like site1.yourserver.com). Optional path segments follow the host name. So if you have the path part “/path/to/page” then “path”, “to”, and “page” would each be a URL segment. Next, after the question mark, the optional query part follows. It consists of one or several “name=value” parameters separated from each other by an ampersand character (‘&’).

Each segment in a URL uses special character encoding, which is named the URL encoding. This encoding ensures that the URL contains only “safe” characters from the ASCII table. If a URL contains unsafe characters, they are replaced with a percentage character (‘%’) followed by two hexadecimal digits (for example, the space character will be replaced by ‘%20’).

Route Types

Routing is a mechanism which allows to map HTTP request to the controller.
With routing, ZF2 knows which of the controller’s action method to execute
as the result of the request. For example, you can map http://localhost/ URL to IndexController::indexAction() method or http://localhost/about URL to IndexController::aboutAction() method.

A typical routing rule has the name, type and options. The name is used to uniquely identify the rule. The type defines the name of the PHP class which implements the algorithm used for comparing the URL string. The options is an array that includes the route string which should be compared against the URL string, and several parameters called the defaults.

In general, the routing algorithm may use any data from HTTP request for matching the route. However, typically, it takes only the URL string (or its substring) as input. The algorithm then compares the URL with the route, and if the URL string matches the route, returns several parameters, including the controller’s name and action method’s name, and possibly others. These parameters may be either hard-coded in a configuration file or grabbed from the URL string. If a certain parameter cannot be retrieved from the URL, its default value is returned.

There are several standard route types provided by Zend Framework 2. These route types are implemented as classes living in the Zend\Mvc\Router\Http namespace.

  • Literal Exact matching against a path part of a URL.
  • Segment Matching against a path segment (or several segments) of a URL.
  • Regex Matching the path part of a URL against a regular expression template.
  • Wildcard Matching the path part of a URL against a key/value pattern.
    Hostname Matching the host name against some criteria.
  • Scheme Matching URL scheme against some criteria.
  • Method Matching an HTTP method (e.g. GET, POST, etc.) against some criteria.

Each route type above (except the Method type) may be matched against a specific segment (or several segments) of a URL. The Method route type is matched against the HTTP method (either GET or POST) retrieved from HTTP request.

There is also the Query route type, which is declared deprecated and is not
recommended to use. This route type is actually not needed, because you can
retrieve query parameters from your URL with the Params controller plugin.

As an example of route definition, let’s consider the Literal route type.

Literal Route Type

With Literal route type, the route match is achieved only when you have the
exact literal match of the route string against the URL path. You typically use the Literal type for URLs which should be short and memorable, like ‘/about’ or ‘/news’.

Below, the definition of the route named “home” is presented. The “home” route is
usually mapped to the “index” action of the IndexController and points to the Home page of your site:

'home' => array(
'type' => 'Zend\Mvc\Router\Http\Literal',
  'options' => array(
    'route'    => '/',
    'defaults' => array(
      'controller' => 'Application\Controller\Index',
      'action'     => 'index',
    ),
  ),
),

Line 2 of this example says that the route’s type is Literal. The actual
route matching algorithm is implemented in the Zend\Mvc\Router\Http\Literal
class. You can either specify the full class name or its short alias (Literal).

Line 4 defines the route string to match against the URL path (the forward slash ‘/’ means the empty URL part). Because we have the literal route type, the route match is achieved only when you have the exact literal path match. For example, if you have the URL http://localhost/ or http://localhost, it will match the ‘/’ route string.

Lines 5-8 define the defaults, which are the parameters returned by the router
if the route matches. The controller and action parameters define the controller and controller’s action method which should be executed. You can also define other parameters here, if needed.

Note: this post is an excerpt from Chapter 5 “URL Routing” of my book Using Zend Framework 2.

Advertisements

I am a software developer currently living in Tomsk, Russia. I received a PhD degree in Computer Science from Tomsk Polytechnic University in 2010. I have been professionally developing C/C++ and PHP software since 2005. I like contributing to open-source and writing programming articles for popular web resources, like CodeProject. Besides writing, I love skiing and watching Formula-1.

Tagged with: ,
Posted in Zend Framework 2

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow ValuableThing on WordPress.com
%d bloggers like this: