Zend and custom routes

One of the classics when working with an MVC based fromwork is extending the frameworks way of handling URL’s (routes), of do not even support this while others have several options like Zend does.One of the things I like about the way Zend handles this is the Zend_Controller_Router_Route_Regex which lets you rewrite your routes using regexp like the name suggests.

Lets say you want to add a classing Rails like route such as example.com/customer/10 where 10 is the ID of a customer. In rails this is considdered a RESTfull route and following a simple convention when designing your routes will reduce the time you spent later on figuring out how they have been setup.

So let’s say we want to implement the above route in Zend. A simple way to do this is by opening up your bootstrap file and add the following:

$router = $frontController->getRouter();
$route = new Zend_Controller_Router_Route_Regex(
	'customer/(\d+)',
	array(
		'controller' => 'customer',
		'action' => 'show'
	),
	array(
		1 => 'id'
	)
);
$router->addRoute('customer', $route);

Which gives you exactly what we want the URL example.com/customer/10 will no call the show action in the customer controller, nice and easy. As you can see, you can easily add more parameters is you like, if you were to rewrite a pager and wanted the keyword in the URL as well something like example.com/customer/super+duper/2 could do the trick.

About these ads

3 responses to “Zend and custom routes

  1. Mukesh

    This is ok to add one route for “customer”

    Now if I want to add another route – how do I that.

    E.g.

    category/category-name – this is first route

    product/product-name.html – this is second route

    product/product-name/comments/ – this is third route

    I am trying to solve this but not getting the idea.

    Thanks
    Mukesh

  2. Ravi

    Should we include this code in the _initAutoLoad or _initViewHelpers()??

  3. Ravi

    Found a simple solution

    $fc = Zend_Controller_Front::getInstance();
    $router = $fc->getRouter();
    $router->addRoute(‘list’, new Zend_Controller_Router_Route(‘/defaultlist’,array(
    ‘controller’ => ‘index’,
    ‘action’ => ‘list’
    )));
    $router->addRoute(‘listPerUser’, new Zend_Controller_Router_Route(‘/list/:user’,array(
    ‘controller’ => ‘index’,
    ‘action’ => ‘list’
    )));
    unset($fc);

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 )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: