Zend Framework: Generating URLs from defined routes
23. Februar 2009
comments feed
The Zend Controller Router allows you to easily create your own routes. That is very useful, but it seems rather unknown, that you can also use these routes to generate URLs according to their definition.
Let's assume you have a route like this:
$controller = Zend_Controller_Front::getInstance();
$router = $controller->getRouter();
$productRoute = new Zend_Controller_Router_Route(
':pid/:name',
array(
'module' => 'default',
'controller' => 'product',
'action' => 'show'
),
array(
'pid' => '\d+'
)
);
$router->addRoute('productpage', $productRoute);
In this route we parse a URL that is supposed to show a product page. The URL will look like http://www.phpdevblog.net/4815162342/Microsoft+Windows+XP+Professional for example. The Router would explode it into pid=4815162342 and name="Microsoft Windows XP Professional"
To generate a URL with the help of the Router you simply need to call the assemble method, which you can either call from the router or the definied route, but keep in mind that you will get different results!
From the router the assemble would look like this:
$link = $router->assemble(
array(
'pid' => '4815162342',
'name' => 'Microsoft Windows XP Professional'
),
'productpage'
);
The result of this method is /4815162342/Microsoft+Windows+XP+Professional
The only difference, if you call the assemble method from the defined route, is that you don't need the route name in the second parameter:
$link = $productRoute->assemble(
array(
'pid' => '4815162342',
'name' => 'Microsoft Windows XP Professional'
)
);
Here the result is 4815162342/Microsoft Windows XP Professional
3 comments
Jennifer
21.04.2009, 00:40 o'clock
Have you checked out the Zend Server CE? What's your take?
recent posts
SeanG
01.04.2009, 18:29 o'clock
This was just what I was looking for!! Thanks for the example code!!