Yii中實(shí)現(xiàn)處理前后臺(tái)登錄的新方法
本文實(shí)例講述了Yii中實(shí)現(xiàn)處理前后臺(tái)登錄的新方法。分享給大家供大家參考,具體如下:
因?yàn)樽罱谧鲆粋€(gè)項(xiàng)目涉及到前后臺(tái)登錄問(wèn)題,我是把后臺(tái)作為一個(gè)模塊(Module)來(lái)處理的。我看很多人放兩個(gè)入口文件index.php和admin.php,然后分別指向前臺(tái)和后臺(tái)。這種方法固然很好,可以將前后臺(tái)完全分離,但我總覺(jué)得這種方式有點(diǎn)牽強(qiáng),這和兩個(gè)應(yīng)用啥區(qū)別?還不如做兩個(gè)App用一個(gè)framework更好。而且Yii官方后臺(tái)使用方法也是使用Module的方式。但是Moudle的方式有一個(gè)很頭疼的問(wèn)題,就是在使用Cwebuser登錄時(shí)會(huì)出現(xiàn)前后臺(tái)一起登錄一起退出的問(wèn)題,這顯然是不合理的。我糾結(jié)了很久才找到下文即將介紹的方法,當(dāng)然,很多也是參考別人的,自己稍作了改動(dòng)。我一開始的做法是在后臺(tái)登錄時(shí)設(shè)置一個(gè)isadmin的session,然后再前臺(tái)登錄時(shí)注銷這個(gè)session,這樣做只能辨別是前臺(tái)登錄還是后臺(tái)登錄,但做不到前后臺(tái)一起登錄,也即前臺(tái)登錄了后臺(tái)就退出了,后臺(tái)登錄了前臺(tái)就退出了。出現(xiàn)這種原因的根本原因是我們使用了同一個(gè)Cwebuser實(shí)例,不能同時(shí)設(shè)置前后臺(tái)session,要解決這個(gè)問(wèn)題就要將前后臺(tái)使用不同的Cwebuser實(shí)例登錄。下面是我的做法,首先看protected->config->main.php里對(duì)前臺(tái)user(Cwebuser)的配置:
'user'=>array( 'class'=>'WebUser',//這個(gè)WebUser是繼承CwebUser,稍后給出它的代碼 'stateKeyPrefix'=>'member',//這個(gè)是設(shè)置前臺(tái)session的前綴 'allowAutoLogin'=>true,//這里設(shè)置允許cookie保存登錄信息,一邊下次自動(dòng)登錄 ),
在你用Gii生成一個(gè)admin(即后臺(tái)模塊名稱)模塊時(shí),會(huì)在module->admin下生成一個(gè)AdminModule.php文件,該類繼承了CWebModule類,下面給出這個(gè)文件的代碼,關(guān)鍵之處就在該文件,望大家仔細(xì)研究:
<?php
class AdminModule extends CWebModule
{
public function init()
{
// this method is called when the module is being created
// you may place code here to customize the module or the application
parent::init();//這步是調(diào)用main.php里的配置文件
// import the module-level models and componen
$this->setImport(array(
'admin.models.*',
'admin.components.*',
));
//這里重寫父類里的組件
//如有需要還可以參考API添加相應(yīng)組件
Yii::app()->setComponents(array(
'errorHandler'=>array(
'class'=>'CErrorHandler',
'errorAction'=>'admin/default/error',
),
'admin'=>array(
'class'=>'AdminWebUser',//后臺(tái)登錄類實(shí)例
'stateKeyPrefix'=>'admin',//后臺(tái)session前綴
'loginUrl'=>Yii::app()->createUrl('admin/default/login'),
),
), false);
//下面這兩行我一直沒(méi)搞定啥意思,貌似CWebModule里也沒(méi)generatorPaths屬性和findGenerators()方法
//$this->generatorPaths[]='admin.generators';
//$this->controllerMap=$this->findGenerators();
}
public function beforeControllerAction($controller, $action)
{
if(parent::beforeControllerAction($controller, $action))
{
$route=$controller->id.'/'.$action->id;
if(!$this->allowIp(Yii::app()->request->userHostAddress) && $route!=='default/error')
throw new CHttpException(403,"You are not allowed to access this page.");
$publicPages=array(
'default/login',
'default/error',
);
if(Yii::app()->admin->isGuest && !in_array($route,$publicPages))
Yii::app()->admin->loginRequired();
else
return true;
}
return false;
}
protected function allowIp($ip)
{
if(empty($this->ipFilters))
return true;
foreach($this->ipFilters as $filter)
{
if($filter==='*' || $filter===$ip || (($pos=strpos($filter,'*'))!==false && !strncmp($ip,$filter,$pos)))
return true;
}
return false;
}
}
?>
AdminModule 的init()方法就是給后臺(tái)配置另外的登錄實(shí)例,讓前后臺(tái)使用不同的CWebUser,并設(shè)置后臺(tái)session前綴,以便與前臺(tái)session區(qū)別開來(lái)(他們同事存在$_SESSION這個(gè)數(shù)組里,你可以打印出來(lái)看看)。
這樣就已經(jīng)做到了前后臺(tái)登錄分離開了,但是此時(shí)你退出的話你就會(huì)發(fā)現(xiàn)前后臺(tái)一起退出了。于是我找到了logout()這個(gè)方法,發(fā)現(xiàn)他有一個(gè)參數(shù)$destroySession=true,原來(lái)如此,如果你只是logout()的話那就會(huì)將session全部注銷,加一個(gè)false參數(shù)的話就只會(huì)注銷當(dāng)前登錄實(shí)例的session了,這也就是為什么要設(shè)置前后臺(tái)session前綴的原因了,下面我們看看設(shè)置了false參數(shù)的logout方法是如何注銷session的:
/**
* Clears all user identity information from persistent storage.
* This will remove the data stored via {@link setState}.
*/
public function clearStates()
{
$keys=array_keys($_SESSION);
$prefix=$this->getStateKeyPrefix();
$n=strlen($prefix);
foreach($keys as $key)
{
if(!strncmp($key,$prefix,$n))
unset($_SESSION[$key]);
}
}
看到?jīng)],就是利用匹配前綴的去注銷的。
到此,我們就可以做到前后臺(tái)登錄分離,退出分離了。這樣才更像一個(gè)應(yīng)用,是吧?嘿嘿…
差點(diǎn)忘了說(shuō)明一下:
Yii::app()->user //前臺(tái)訪問(wèn)用戶信息方法 Yii::app()->admin //后臺(tái)訪問(wèn)用戶信息方法
不懂的仔細(xì)看一下剛才前后臺(tái)CWebUser的配置。
附件1:WebUser.php代碼:
<?php
class WebUser extends CWebUser
{
public function __get($name)
{
if ($this->hasState('__userInfo')) {
$user=$this->getState('__userInfo',array());
if (isset($user[$name])) {
return $user[$name];
}
}
return parent::__get($name);
}
public function login($identity, $duration) {
$this->setState('__userInfo', $identity->getUser());
parent::login($identity, $duration);
}
}
?>
附件2:AdminWebUser.php代碼
<?php
class AdminWebUser extends CWebUser
{
public function __get($name)
{
if ($this->hasState('__adminInfo')) {
$user=$this->getState('__adminInfo',array());
if (isset($user[$name])) {
return $user[$name];
}
}
return parent::__get($name);
}
public function login($identity, $duration) {
$this->setState('__adminInfo', $identity->getUser());
parent::login($identity, $duration);
}
}
?>
附件3:前臺(tái)UserIdentity.php代碼
<?php
/**
* UserIdentity represents the data needed to identity a user.
* It contains the authentication method that checks if the provided
* data can identity the user.
*/
class UserIdentity extends CUserIdentity
{
/**
* Authenticates a user.
* The example implementation makes sure if the username and password
* are both 'demo'.
* In practical applications, this should be changed to authenticate
* against some persistent user identity storage (e.g. database).
* @return boolean whether authentication succeeds.
*/
public $user;
public $_id;
public $username;
public function authenticate()
{
$this->errorCode=self::ERROR_PASSWORD_INVALID;
$user=User::model()->find('username=:username',array(':username'=>$this->username));
if ($user)
{
$encrypted_passwd=trim($user->password);
$inputpassword = trim(md5($this->password));
if($inputpassword===$encrypted_passwd)
{
$this->errorCode=self::ERROR_NONE;
$this->setUser($user);
$this->_id=$user->id;
$this->username=$user->username;
//if(isset(Yii::app()->user->thisisadmin))
// unset (Yii::app()->user->thisisadmin);
}
else
{
$this->errorCode=self::ERROR_PASSWORD_INVALID;
}
}
else
{
$this->errorCode=self::ERROR_USERNAME_INVALID;
}
unset($user);
return !$this->errorCode;
}
public function getUser()
{
return $this->user;
}
public function getId()
{
return $this->_id;
}
public function getUserName()
{
return $this->username;
}
public function setUser(CActiveRecord $user)
{
$this->user=$user->attributes;
}
}
附件4:后臺(tái)UserIdentity.php代碼
<?php
/**
* UserIdentity represents the data needed to identity a user.
* It contains the authentication method that checks if the provided
* data can identity the user.
*/
class UserIdentity extends CUserIdentity
{
/**
* Authenticates a user.
* The example implementation makes sure if the username and password
* are both 'demo'.
* In practical applications, this should be changed to authenticate
* against some persistent user identity storage (e.g. database).
* @return boolean whether authentication succeeds.
*/
public $admin;
public $_id;
public $username;
public function authenticate()
{
$this->errorCode=self::ERROR_PASSWORD_INVALID;
$user=Staff::model()->find('username=:username',array(':username'=>$this->username));
if ($user)
{
$encrypted_passwd=trim($user->password);
$inputpassword = trim(md5($this->password));
if($inputpassword===$encrypted_passwd)
{
$this->errorCode=self::ERROR_NONE;
$this->setUser($user);
$this->_id=$user->id;
$this->username=$user->username;
// Yii::app()->user->setState("thisisadmin", "true");
}
else
{
$this->errorCode=self::ERROR_PASSWORD_INVALID;
}
}
else
{
$this->errorCode=self::ERROR_USERNAME_INVALID;
}
unset($user);
return !$this->errorCode;
}
public function getUser()
{
return $this->admin;
}
public function getId()
{
return $this->_id;
}
public function getUserName()
{
return $this->username;
}
public function setUser(CActiveRecord $user)
{
$this->admin=$user->attributes;
}
}
希望本文所述對(duì)大家基于Yii框架的PHP程序設(shè)計(jì)有所幫助。
- Yii2下點(diǎn)擊驗(yàn)證碼的切換實(shí)例代碼
- Yii2簡(jiǎn)單實(shí)現(xiàn)給表單添加驗(yàn)證碼的方法
- Yii2增加驗(yàn)證碼步驟詳解
- yii2中添加驗(yàn)證碼的實(shí)現(xiàn)方法
- Yii使用Captcha驗(yàn)證碼的方法
- yii實(shí)現(xiàn)創(chuàng)建驗(yàn)證碼實(shí)例解析
- Yii2實(shí)現(xiàn)多域名跨域同步登錄退出
- Yii框架用戶登錄session丟失問(wèn)題解決方法
- Yii2框架實(shí)現(xiàn)注冊(cè)和登錄教程
- Yii2中OAuth擴(kuò)展及QQ互聯(lián)登錄實(shí)現(xiàn)方法
- Yii框架登錄流程分析
- Yii框架實(shí)現(xiàn)的驗(yàn)證碼、登錄及退出功能示例
相關(guān)文章
基于PHP的簡(jiǎn)單采集數(shù)據(jù)入庫(kù)程序
前幾天有一朋友要我?guī)妥鲆粋€(gè)采集新聞信息的程序,抽了點(diǎn)時(shí)間寫了個(gè)PHP版本的,隨筆記錄下。2014-07-07
用Laravel輕松處理千萬(wàn)級(jí)數(shù)據(jù)的方法實(shí)現(xiàn)
這篇文章主要介紹了用Laravel輕松處理千萬(wàn)級(jí)數(shù)據(jù)的方法實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12
Zend Framework校驗(yàn)器Zend_Validate用法詳解
這篇文章主要介紹了Zend Framework校驗(yàn)器Zend_Validate用法,結(jié)合實(shí)例形式分析了校驗(yàn)器Zend_Validate的功能、使用技巧與相關(guān)注意事項(xiàng),需要的朋友可以參考下2016-12-12
Laravel中基于Artisan View擴(kuò)展包創(chuàng)建及刪除應(yīng)用視圖文件的方法
這篇文章主要介紹了Laravel中基于Artisan View擴(kuò)展包創(chuàng)建及刪除應(yīng)用視圖文件的方法,簡(jiǎn)單分析了Laravel擴(kuò)展包的安裝及視圖的創(chuàng)建與刪除操作相關(guān)技巧,需要的朋友可以參考下2016-10-10
Laravel框架控制器的request與response用法示例
這篇文章主要介紹了Laravel框架控制器的request與response用法,結(jié)合實(shí)例形式分析了Laravel框架控制器的request與response發(fā)送請(qǐng)求及響應(yīng)請(qǐng)求的相關(guān)操作技巧,需要的朋友可以參考下2019-09-09
淺談php數(shù)組array_change_key_case() 函數(shù)和array_chunk()函數(shù)
下面小編就為大家?guī)?lái)一篇淺談php數(shù)組array_change_key_case() 函數(shù)和array_chunk()函數(shù)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-10-10
PHP使用opendir和readdir函數(shù)讀取指定目錄下所有文件
這篇文章主要介紹了PHP使用opendir和readdir函數(shù)讀取指定目錄下所有文件實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08

