lautr.com

Hannes Blog for Development and Stuff besides

modifying the zend framework router, an example for a simple website

| Keine Kommentare

I’m currently working on a new Site on the base of zend framework (again ;) ). But since the normal url Structure (controller/action) has a little bit of an overhead i looked into how to modify the router. To my surprise i found out that is extremely simple. I decided to go with the “Zend_Controller_Router_Route_Regex” as the name suggests it uses regexp.

The Url structure i was aiming for is this:

http://www.example.com

http://www.example.com/some-article.html

http://www.example.com/somepage

http://www.example.com/taxonomyvocabulary/taxonomyelement

For that purpose i added the following to my bootstrap.php

$ctrl  = Zend_Controller_Front::getInstance();
$router = $ctrl->getRouter(); // returns a rewrite router by default

$route['index'] = new Zend_Controller_Router_Route_Regex(
'',
array(
'controller' => 'index',
'action'     => 'index'
)
);
$route['page'] = new Zend_Controller_Router_Route_Regex(
'([^/\.]+)',
array(
'controller' => 'index',
'action'     => 'page'
)
);
$route['article'] = new Zend_Controller_Router_Route_Regex(
'([^\.]+)\.html',
array(
'controller' => 'index',
'action'     => 'article'
)
);
$route['taxonomy'] = new Zend_Controller_Router_Route_Regex(
'([^/\.]+)/([^/\.]+)',
array(
'controller' => 'index',
'action'     => 'taxonomy'
)
);
$route['error404'] = new Zend_Controller_Router_Route_Regex(
'.*',
array(
'controller' => 'index',
'action'     => 'error404'
)
);
$router->addRoute('error404',   $route['error404']);
$router->addRoute('index',      $route['index']);
$router->addRoute('page',       $route['page']);
$router->addRoute('article',    $route['article']);
$router->addRoute('taxonomy',   $route['taxonomy']);

Not that zend automatically adds a ^ to the start and an $ to the end of any regexp so there is no need to do that. I also added an 404 Action to take care of any Request that does not match one of the given patterns, the routes are checked in the order they are added, the last match is used, so i added the 404 Action at first.

Autor: Hannes

Hi! I’m Johannes Lauter a 26 year old Web Application Developer based in Berlin ... more

Hinterlasse eine Antwort

Pflichtfelder sind mit * markiert.

*