PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Basic Rewrite Router Operation

The heart of the RewriteRouter is the definition of user defined routes. Routes are added by calling the addRoute method of RewriteRouter and passing in a new instance of a class implementing Zend_Controller_Router_Route_Interface. Eg.:

<?php
$router
->addRoute('user',
                  new 
Zend_Controller_Router_Route('user/:username'));

Rewrite Router comes with six basic types of routes (one of which is special):

Routes may be used numerous times to create a chain or user defined application routing schema. You may use any number of routes in any configuration, with the exception of the Module route, which should rather be used once and probably as the most generic route (i.e., as a default). Each route will be described in greater detail later on.

The first parameter to addRoute is the name of the route. It is used as a handle for getting the routes out of the router (e.g., for URL generation purposes). The second parameter being the route itself.

Note

The most common use of the route name is through the means of Zend_View url helper:


<a href=
"<?php echo $this->url(array('username' => 'martel'), 'user'?>">Martel</a>

Which would result in the href: user/martel.

Routing is a simple process of iterating through all provided routes and matching its definitions to current request URI. When a positive match is found, variable values are returned from the Route instance and are injected into the Zend_Controller_Request object for later use in the dispatcher as well as in user created controllers. On a negative match result, the next route in the chain is checked.

If you need to determine which route was matched, you can use the getCurrentRouteName() method, which will return the identifier used when registering the route with the router. If you want the actual route object, you can use getCurrentRoute().

Reverse Matching

Routes are matched in reverse order so make sure your most generic routes are defined first.

Returned Values

Values returned from routing come from URL parameters or user defined route defaults. These variables are later accessible through the Zend_Controller_Request::getParam() or Zend_Controller_Action::_getParam() methods.

There are three special variables which can be used in your routes - 'module', 'controller' and 'action'. These special variables are used by Zend_Controller_Dispatcher to find a controller and action to dispatch to.

Special Variables

The names of these special variables may be different if you choose to alter the defaults in Zend_Controller_Request_Http by means of the setControllerKey() and setActionKey() methods.

Zend Framework