Using Zend_Controller_Router_Interface to create pretty URLs

December 17th 2012

Zend Framework makes it incredibly easy to route various URLs to different areas of your application.

There are some standard routes that I use, but for some reason there are many developers who don't harness this power of Zend.

The time to overhaul your URLs is now.

To get started, add an action to your Bootstrap.php called _initRouter()

PHP Code:
<?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{

    protected function 
_initRouter()
    {

    }

}

The first step is to retrieve the Zend_Controller_Router_Interface from the Zend_Controller_Front object.

Add this to your _initRouter() method.

PHP Code:
<?php
        $fc 
Zend_Controller_Front::getInstance();
        
$router $fc->getRouter(); // Retrieve Zend_Controller_Router_Interface

Now, the exciting part! Let's create some basic routes.

PHP Code:
<?php
        $router
->addRoute'login' , new Zend_Controller_Router_Route('/login',
                            array(
                                    
'module' => 'default',
                                    
'controller' => 'index',
                                    
'action' => 'login'
                            
)));
        
$router->addRoute'logout' , new Zend_Controller_Router_Route('/logout',
                array(
                        
'module' => 'default',
                        
'controller' => 'index',
                        
'action' => 'logout'
                
)));

The routes above mean that if a user requests the path '/login' then they will actually be routed to:

Text Snippet:
IndexController::loginAction()

The second route would handle all requests to '/logout'. These would be routed to:

Text Snippet:
IndexController::logoutAction()

Ready to kick it up a gear? The Zend_Controller_Router_Interface also makes it incredibly easy to assign request parameters without having to mess around with keys in a URL.

For example, if you added this route to your _initRouter() method:

PHP Code:
<?php
        $router
->addRoute'userprofile' , new Zend_Controller_Router_Route('/profile/:userid',
                array(
                        
'module' => 'default',
                        
'controller' => 'index',
                        
'action' => 'profile'
                
)));

Then all requests matching '/profile/xxxx' would be sent to:

Text Snippet:
IndexController::profileAction()

But there's something special going on here. Inside of profileAction() you could call the 'userid' request param directly and retrieve its value.

PHP Code:
<?php
$userId 
$this->getRequest()->getParam('userid',null);

The variable $userId would now contain whatever came after '/profile/' in the Url.

You can really get creative with Routes, and I've hardly touched the surface of the capability, but as you can see, this is absolutely simple.