Home / Zend Framework Controller Router example

Zend Framework Controller Router example

The first MVC framework I used was Code Igniter but I’ve decided to give the Zend Framwork a go because I like their approach to use what you need, and after some studying of the controllers and view functionality those parts do more or less exactly what I want. There are ways to add additional routes to the controllers but I couldn’t work out initially how to inject them into the controller from the Zend Framwork documentation. This post shows the original example from the Zend Framework documentation and then a more full example which I constructed using other sources.

This is the original example from the Zend Framwork documentation, in the standard router section, with my own bolding added – see below for details.

/* Create a router */
$router = $ctrl->getRouter(); // returns a rewrite router by default
$router->addRoute(
    'user',
    new Zend_Controller_Router_Route('user/:username', array('controller' => 'user', 'action' => 'info'))
);

 I couldn’t work out what $ctrl had come from (which I have bolded in the example above) and it wasn’t mentioned in the preceding examples or sections. After a little searching on Google, I found some useful examples and got an additional route working, realising that $ctrl was a handle to the controller.

Here’s a full example of a bootstrap file, assigning an additional route to the controller:

set_include_path('../library' . PATH_SEPARATOR . get_include_path());

require_once 'Zend/Controller/Front.php';    
require_once 'Zend/Controller/Router/Route.php';    

$ctrl  = Zend_Controller_Front::getInstance();
$router = $ctrl->getRouter();

$route = new Zend_Controller_Router_Route(
    'user/:username',
    array(
        'controller' => 'user',
      	'action'     => 'info'
    )
);
$router->addRoute('user', $route);

$ctrl->run('../controllers');

It could also be shortened to be more like the original example like so:

set_include_path('../library' . PATH_SEPARATOR . get_include_path());

require_once 'Zend/Controller/Front.php';    
require_once 'Zend/Controller/Router/Route.php';    

$ctrl  = Zend_Controller_Front::getInstance();

$router = $ctrl->getRouter();
$router->addRoute(
    'user',
    new Zend_Controller_Router_Route('user/:username', array('controller' => 'user', 'action' => 'info'))
);

$ctrl->run('../controllers');

I’ve only just started using the Zend Framwork, so there may be better ways of doing the above but for now it seems to work just fine for me.