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.
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
Should we include this code in the _initAutoLoad or _initViewHelpers()??
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);