1)創建BaseController控制器繼承Controller(後台的一切操作要繼承BaseController):
在BaseController裡面添加:
復制代碼 代碼如下:
public function checkLogin() {
if (Yii::app()->authority->isLogin() == Yii::app()->authority->getStatus('NOTLOGIN')) {
$url = $this->createUrl('user/login');
if (Yii::app()->request->isPostRequest && Yii::app()->request->isAjaxRequest) {
echo json_encode(array('code' => -101, 'message' => '用戶未登錄。', 'callback' => 'window.location="' . $url . '";'));
} else if (Yii::app()->request->isAjaxRequest) {
echo '<script language="javascript">window.location="' . $url . '";</script>';
} else {
$this->redirect($url);
}
exit;
}
return true;
}
在components目錄下創建Authority.php文件:
復制代碼 代碼如下:
<?php
/**
* 權限檢查組件
*/
class Authority extends CComponent {
private $NOTLOGIN = -1;
private $FAILED = -2;
private $PASS = 1;
public function init() {
}
/**
* 檢查是否登陸
* @return boolean
*/
function isLogin() {
return isset(Yii::app()->session['user']) ? $this->PASS : $this->NOTLOGIN;
}
/**
* 獲取狀態值
* @param string $name
* @return int
*/
public function getStatus($name){
return $this->$name;
}
}