Custom Routes with Zend_Controller_Router_Route

Rewrite The Url?

Actually this is really a common task to do. You’ve to rewrite the url to be more “user friendly”. To be more clear I’ll give you an example. Let’s imagine you have a index controller and an index action. Thus if you have to load an Id from the database at least with the build in Zend Framework capabilities, you’ve to use this link:

www.example.com/index/index/id/33949

This is not good. It’s really bad. It will be great if you can use something like this:

www.example.com/33949

The solution in Zend Framework is called Zend_Controller_Router_Route. In a short snippet this will look like so:

$frontController->addRoute("my-route", new Zend_Controller_Router_Route("/:id",
    array("controller" => "index", "action" => "index", 'id' => 1),
    array('id' => '\d+')));

Here as you can see id is set to be 1. But don’t worry that’s not a hard code. The real work is done by the last parameter where the id is matched against a number value. Thus www.example.com/3 will be OK, but www.example.com/3a won’t.

Important Note

Don’t forget to add this rewrite rule in the .htaccess file.

6 thoughts on “Custom Routes with Zend_Controller_Router_Route

  1. I have a question about zend router
    Now i write a multi language site using zend, and my site have multiple controller such as: news, products
    i want set router
    for url rewrite like that:
    example: when user browse my website in english, and he click on the link washing machine to view a product that have id=14, title=”washing machine” in then the url will become:
    localhost:8089/test/en/products/index/14-washing-machine.html

    when user browse my website in Italia, and he click on the link washing machine to view a product that have id=15, title=”lavatrice” in then the url will become:
    localhost:8089/test/it/products/index/15-lavatrice.html

    In the products i will get the lang, id parameters and get the suitable content to display to user.

    Similar with news controller
    How do i implement the router for my controller such as products, news

    Could you help me

  2. Where to update this

    $frontController->addRoute("my-route", new Zend_Controller_Router_Route("/:id",
        array("controller" => "index", "action" => "index", 'id' => 1),
        array('id' => '\d+')));
    

    Code in Bootstrap.php?

Leave a Reply

Your email address will not be published. Required fields are marked *