December9
Working with Zend Framework is fun, but sometimes very small tasks like adding a custom regex route becomes annoying.
A simple solution is obvious, create a simple .htaccess like file without using .htaccess.
This is sample code to add a new regex route to Zend Framework by placing this method in bootstrap class.
protected function _initLoadUrls()
{
//get instance of front controller
$front = Zend_Controller_Front::getInstance();
//get current router
$router = $front->getRouter();
//remove default routes if you want
$router->removeDefaultRoutes();
//create new regex route
$route = new Zend_Controller_Router_Route_Regex('([0-9a-zA-z-]+)/([0-9a-zA-z-]+)\.html',array('controller' => 'product','action' => 'index'),array(1=>'category_slug',2=>'product_slug'),'%s/%s.html');
//add to router
$router->addRoute($key, $route);
}
Now for the solution i will create a file say url-rules.php in zend/application/config folder having an associative array which is.
$rules=array(
'home' =>array('',array('controller' => 'index','action' => 'home'),null,''),
'product' =>array('([0-9a-zA-z-]+)/([0-9a-zA-z-]+)\.html',array('controller' => 'product','action' => 'index'),array(1=>'category_slug',2=>'product_slug'),'%s/%s.html'),
'category' =>array('category/([0-9a-zA-z-]+).html',array('controller' => 'category','action' => 'index'),array(1=>'category_slug'),'category/%s.html'),
'brand' =>array('brand/([0-9a-zA-z-]+).html',array('controller' => 'brand','action' => 'index'),array(1=>'brand'),'brand/%s.html'),
'page' =>array('([0-9a-zA-z-]+).html',array('controller' => 'page','action' => 'index'),array(1=>'page_slug'),'%s.html')
);
Now just by editing the previous method from bootstrap class.
protected function _initLoadUrls()
{
//get instance of front controller
$front = Zend_Controller_Front::getInstance();
require_once(APPLICATION_PATH."/configs/url-rules.php");
if(count($rules))
{
//get current router
$router = $front->getRouter();
//remove default routes if you want
$router->removeDefaultRoutes();
//pars through the assosiative urls array
foreach($rules as $key=>$value)
{
//create new regex route
$route = new Zend_Controller_Router_Route_Regex($value[0],$value[1],$value[2],$value[3]);
//add to current router
$router->addRoute($key, $route);
}
}
}
Ta-Da problem solved.