Creating custom friendly URLs using the Zend framework is really simple. The default routing setup for Zend is : ‘:module/:controller/:action/*’, (* will match any var/value) which is fine for most setups. However on some pages having the var/value might not look very good, for example this url is not very readable:
/popular/index/type/images/page/1/sortOrder/alltime (controller/action/var/value/var/value/var/value)
We would prefer something like this:
/popular/images/1/alltime
Luckily Zend provides a very flexible router that we can configure as we want. To start with, we create a new config file called routes.ini, and adds these lines:
-
-
routes.popular.route = popular/:type/:page/:sortOrder
-
routes.popular.defaults.controller = popular
-
routes.popular.defaults.action = index
-
routes.popular.defaults.type = images
-
routes.popular.defaults.sortOrder = alltime
-
routes.popular.defaults.page = 1
-
routes.popular.reqs.type = \w+
-
routes.popular.reqs.page = \d+
-
routes.popular.reqs.sortOrder = \w+
-
routes.popular.route tells us what to match. routes.popular.defaults.* sets default values for the variables (if none are given in the url). routes.popular.reqs.* sets requirements on the variables, for example that page must be a number.
The last thing we need to do is add a few lines to our bootstrap.php:
-
-
$config = new Zend_Config_Ini(APPLICATION_PATH . ‘/config/routes.ini’);
-
$router = $frontController->getRouter();
-
$router->addConfig($config,‘routes’);
-
If you want to learn more about the Zend Framework: