————在Yii中我們可以使用PHP超級全局變量像$_SERVER,$_GET或者$_POST來直接響應請求數據,但是是更好的方法是使用Yii強大的 CHttpRequest 類,它解決了在各種不同服務器中的不一致性,管理cookies,提供一些額外的安全性和一套給力的面向對象方法。
我們可以使用Yii::app()->getRequest()來請求 CHttpRequest 組件。
—下面是 CHttpRequest 對 URL 操作的一些方法。在下面的表格中,我們用粗體字樣標記了返回的部分。
getUrl | http://yiibook.local/test/index?var=val |
getHostInfo | http://yiibook.local/test/index?var=val |
getPathInfo | http://yiibook.local/test/index?var=val |
getRequestUri | http://yiibook.local/test/index?var=val |
getQueryString | http://yiibook.local/test/index?var=val |
—CHttpRequest確保請求類型的方法:
——getIsPostRequest——返回是否這是一個POST請求。
——getIsAjaxRequest——返回這是否是一個AJAX請求。
——getRequestType——返回請求類型,比如 GET POST HEAD PUT DELETE.。
例如,我們可以使用 getIsAjaxRequest 來根據請求類型響應不同的內容:
class TestController extends CController
{
public function actionIndex()
{
if(Yii::app()->request->isAjaxRequest) //等價於<strong>Yii::app()->getRequest()</strong>
$this->renderPartial('test');
else
$this->render('test');
}
}
在上面的代碼中,如果請求是通過AJAX,我們就渲染了一個沒有佈局的視圖。
—儘管PHP爲POST和GET都提供了超全局變量,但 CHttpRequest 的對應方法則允許我們省略一些額外的檢查:
——getParam——返回指定GET或POST參數值。(public mixed getParam(string $name, mixed $defaultValue=NULL)
——getQuery——返回指定GET參數值。(getQuery(string $name, mixed $defaultValue=NULL)
——getPost——返回指定POST參數值。(string $name, mixed $defaultValue=NULL)
上面的 defaultValue 在默認參數值不存在時生效。下面是個簡單的例子:
class TestController extends CController
{
public function actionIndex()
{
$request = Yii::app()->request;
$param = $request->getParam('id', 1);
// 等價於
$param = isset($_REQUEST['id']) ? $_REQUEST['id'] : 1;
$param = $request->getQuery('id');
// 等價於
$param = isset($_GET['id']) ? $_GET['id'] : null;
$param = $request->getPost('id', 1);
// 等價於
$param = isset($_POST['id']) ? $_POST['id'] : 1;
}
}
——延伸一下:sendfile()方法。向用戶發送一個文件。
class TestController extends CController
{
public function actionIndex()
{
$request = Yii::app()->getRequest();
$request->sendFile('test.txt', 'File content goes here.');
}
}
——最後要看一下 getCookies 方法。它返回一個CCookieCollection類實例,這個實例允許我們處理 cookies。因爲CCookieCollection繼承自CMap,所以我們可以使用一些原始的PHP方法:
class TestController extends CController
{
public function actionIndex()
{
$request = Yii::app()->request;
// 獲取cookie
$cookie = $request->cookies['test'];
if($cookie)
// 打印 cookie 值
echo $cookie->value;
else {
// 創建一個cookie實例
$cookie=new CHttpCookie('test','I am a cookie!');
$request->cookies['test'] = $cookie;
}
}
}
如果你有很多cookie值要處理,並且想精簡代碼,你可以使用像這樣的助手方法:
class Cookie
{
public static function get($name)
{
$cookie=Yii::app()->request->cookies[$name];
if(!$cookie)
return null;
return $cookie->value;
}
public static function set($name, $value, $expiration=0)
{
$cookie=new CHttpCookie($name,$value);
$cookie->expire = $expiration;
Yii::app()->request->cookies[$name]=$cookie;
}
}
在你把這份代碼放到 protected/components/Cookie.php 後,我們就可以這樣做:
class TestController extends CController
{
public function actionIndex()
{
$cookie = Cookie::get('test');
if($cookie)
echo $cookie;
else
Cookie::set('test','I am a cookie!!');
}
}