(为什么)不应该在Yii应用程序的控制器中直接访问请求参数?

时间:2014-08-13 16:45:26

标签: php yii get httprequest http-request-parameters

有几种方法可以在控制器中访问请求参数:

direcly

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

对请求对象

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

(为什么)具有请求对象的变体是否更好?

1 个答案:

答案 0 :(得分:1)

Web Request类表示一个HTTP请求,它封装了$ _SERVER变量并解决了它在不同Web服务器之间的不一致。

/**
 * 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);
}