0

There are several ways to access the request parameters within a controller:

direcly

class MyController extends \CController
{
    ...
    public function actionMy()
    {
        ...
        $myVar = $_GET['my_param'];
        ...
    }
    ...
}

over the request object

class MyController extends \CController
{
    ...
    public function actionMy()
    {
        ...
        $myVar = $this->request->params('my_param');
        ...
    }
    ...
}

(Why) Is the variant with the request object better?

automatix
  • 14,018
  • 26
  • 105
  • 230

1 Answers1

1

The web Request class represents an HTTP request it encapsulates the $_SERVER variable and resolves its inconsistency among different Web servers.

/**
 * Returns the named GET or POST parameter value.
 * If the GET or POST parameter does not exist, the second parameter to this method will be returned.
 * If both GET and POST contains such a named parameter, the GET parameter takes precedence.
 * @param string $name the GET parameter name
 * @param mixed $defaultValue the default parameter value if the GET parameter does not exist.
 * @return mixed the GET parameter value
 * @see getQuery
 * @see getPost
 */
public function getParam($name,$defaultValue=null)
{
    return isset($_GET[$name]) ? $_GET[$name] : (isset($_POST[$name]) ? $_POST[$name] : $defaultValue);
}
Sean Keane
  • 411
  • 1
  • 6
  • 19
  • Thank you for the explanation! But what is the advantage of this approach? – automatix Aug 13 '14 at 22:13
  • I've updated my answer to show you the actual source code. Basically the advantage is that it will check both get and post, you can set a default value, and it does an isset. – Sean Keane Aug 13 '14 at 22:40