25

Can anyone explain the differences both functionally and in terms of good/bad practice whhy one of these should be preferred over the other:

$getParam = Mage::app()->getRequest()->getParam('getparam');

v

$getParam = $_GET['getparam'];
Marty Wallace
  • 34,046
  • 53
  • 137
  • 200

2 Answers2

39

There is a significant difference between the two. $_GET is simply an array, like $_POST. However, calling Mage::app()->getRequest()->getParam('param_name') will give you access to both GET and POST (DELETE and PUT are not included here) - see code below:

lib/Zend/Controller/Request/Http.php

public function getParam($key, $default = null)
{
    $keyName = (null !== ($alias = $this->getAlias($key))) ? $alias : $key;

    $paramSources = $this->getParamSources();
    if (isset($this->_params[$keyName])) {
        return $this->_params[$keyName];
    } elseif (in_array('_GET', $paramSources) && (isset($_GET[$keyName]))) {
        return $_GET[$keyName];
    } elseif (in_array('_POST', $paramSources) && (isset($_POST[$keyName]))) {
        return $_POST[$keyName];
    }

    return $default;
}

In addition, if the system sets other params with Mage::app()->getRequest()->setParam(), it becomes accessible via the getParam() function. In Magento you want to always use getParam().

Joseph at SwiftOtter
  • 4,276
  • 5
  • 37
  • 55
  • 2
    Also gives access to params parsed from the url e.g. site.com/foo/bar/baz/bip/bop/boom/bum would have params bip = bop and boom = bum – benmarks Nov 23 '12 at 19:43
  • Ah, yes - can't believe I missed that :) – Joseph at SwiftOtter Nov 23 '12 at 20:48
  • And what exacly IS a "param", if not a request parameter (part of the url)? Why would you use `setParam()`? – Buttle Butkus Oct 28 '15 at 00:57
  • A param in Magento is a helper for a combined array of the values found in the url, GET and POST variables. I don't see much usage for `setParam()` other than to filter or parse values before they get to the system (in a `predispatch` observer). That isn't something that is used often, but it is helpful when you need it. – Joseph at SwiftOtter Oct 28 '15 at 15:46
6
Mage::app()->getRequest()->getParam('getparam');

Will return you 'getparam' if it is send with GET, POST (not sure about DELETE, PUT ...) request. Did not work with Magento but if there parameters that sent through routing. I would expect them also being accessible through that function.

$_GET contains only parameters sent through GET

$_POST contains only parameters sent through POST

E_p
  • 3,136
  • 16
  • 28
  • `$_GET` contains params from the querystring regardless of request method. `$_POST` contains params from the request body **if** the `Content-Type` header of the request was `application/x-www-form-urlencoded` and the request method was `POST` – Esailija Nov 23 '12 at 18:11
  • You can POST Content type json ;) – E_p Nov 23 '12 at 18:12