Tuesday, March 2, 2010

Interesting issue of Zend_Request Object

See the code below:
class TestController extends Zend_Controller_Action
public function testAction()
$params = $this->getRequest()->getParams();

It tries to get all parameters of a request. In most situations, it works fine. However, if the request contains a parameter like '?action=subscribe', and you try to get $action = $params['action']. Now, what do you think is the value of $action? If you say, it must be 'subscribe', then you are wrong.

How come this happen? The answer is, Zend_Request object set 3 default parameters: 'module', 'controller' and 'action', and they will overwrite the identified variables in the request. Back to the code above, if you var_dump($params), you probably will see the result like:
array(3) {
['module'] => string(7) "default"
['controller'] => string(5) "test"
['action'] => string(5) "test"

As you can see, the value of $action will be 'test'. What if we try to do $action = $this->getRequest()->getParam('action')? This doesn't help either, the value of $action is still 'test' instead of 'subscribe'. Same applies to $this->_getAllParams() and $this->_getParam().

So how do we get the correct value of action in the request? The answer is, for a POST request, we must exactly use $this->getRequest()->getPost('action'); for a GET request, we must use $this->getRequest()->getQuery('action')

No comments: