zend-frameworkurl-rewritingzend-routezend-viewzend-router

Zend Routing / URL helper . Have a global parameter show up first in URL


Was curious if anyone knew the best way to implement the following: I have a parameter in my zend framework 1.12 app which effectively controls the 'scope' of things, and is a field in every table in my db to represent the scope of a row. It is a simple integer variable, and can be thought of as 'buildingID', so it controls which 'building' we are working with.

In a plugin, I have:

Zend_Controller_Front::getInstance()->getRouter()->setGlobalParam('building', DYNAMIC_INT);

which accomplishes what I need. When I build a URL with the URL view-helper I have my parameter, but it is always at the end of the parameter list. I know this is trivial from a programming perspective, but how would I achieve 'prepending' this global param to my url parameters?

site.com/admin/controller/action/param1/xyz/param2/xyz/building/2

to become

site.com/admin/controller/action/building/2/param1/xyz/param2/xyz ?

Open to any ideas. If you want me to overload the url view helper, can you provide some example code, because I had trouble setting up this class.

Thank you all!


Solution

  • You can use a custom route to accomplish this. Setup the route somewhere in your bootstrap file:

    $route = new Zend_Controller_Router_Route(
        ':controller/:action/building/:building/*'
    );
    $router = Zend_Controller_Front::getInstance()->getRouter();
    $router->addRoute('building', $route);
    

    And then, assuming that the following has been called at some point prior to using the url view helper...

    Zend_Controller_Front::getInstance()->getRouter()->setGlobalParam('building', DYNAMIC_INT);
    

    ...you can specify the route as the second argument of the helper:

    echo $this->url(array(
        'controller' => 'admin',
        'action' => 'controller',
        'param1' => 'xyz',
        'param2' => 'xyz',
    ), 'building');
    
    // /admin/controller/building/1/param1/xyz/param2/xyz