Friday, April 29, 2011

Zend Framework: How to get default param?

How do I get the 'default' param if not specified?

Consider the following:

http://localhost/controller/action/id/123

In my controller, I can get the value of 'id' using

$request = $this->getRequest();
$id = $request->getParam('id');

If the URL is

http://localhost/controller/action/456

how do I get the value of 456? What is the 'param' name?

From stackoverflow
  • By default ZF URL have to follow pattern:

    /controller/action/param1Name/param1Val/param2Name/param2Val ...
    

    You should use router. For example in bootstrap.php:

    $frontController = Zend_Controller_Front::getInstance(); 
    //^^^this line should be already there
    
    $router = $frontController->getRouter();
    $route = new Zend_Controller_Router_Route(
        'yourController/yourAction/:id',
        array(
            'id'       => 1, //default value
            'controller' => 'yourController',
            'action'     => 'yourAction'
        ),
        array('id' => '\d+')
    );
    $router->addRoute('yourController', $route);
    
    uuɐɯǝʃǝs : Where exactly should I add this router? In the doc says in Controller. Is it controllers/myController.php? or in bootstrap.php file? TQ!
    vartec : it's referring to frontend controller
    uuɐɯǝʃǝs : Thank you. Just to share that I need to put all this before dispatching the front controller. // Dispatch the request using the front controller. $frontController->dispatch ();
  • try to add this route to router:

    $route = new Zend_Controller_Router_Route_Regex(
        'my_controller/my_action/(\d+)',
        array(
            'controller' => 'my_controller',
            'action'     => 'my_action'
        )
    );
    
    $router->addRoute('my_route', $route);
    
    uuɐɯǝʃǝs : Where exactly should I add this router? In the doc says in Controller. Is it controllers/myController.php?
    David Caunt : Vartec's route is more efficient and better in this case
  • Just want to share.

    The above router setting must be used with the $frontController.

    And be sure put it before the controller dispatches.

    <..above router code goes here...>
    
    // Dispatch the request using the front controller. 
    $frontController->dispatch ();
    

    Hope don't waste time like myself. ;-)

    vartec : Of course. That's why I've suggested putting that in bootstrap.php, which is called before dispatching.

0 comments:

Post a Comment