yii 的確是一個強大而臃腫的框架,簡單的小項目,或者只做后台接口調用的項目,建議不要用。
今天記錄一下yii使用中cwebuser(Yii::app()->user->login())登錄;
1、准備工作
官方標准做法,在components里加一個UserIdentity.php文件,class UserIdentity extends CUserIdentity
繼承CUserIdentity,然后在UserIdentity類里面寫驗證的業務過程(比如你在哪張表去查數據,取數據之類)
2、開始登錄
new 一個UserIdentity,傳入參數,然后執行驗證方法
例:
$this->_identity=new UserIdentity($this->username,$this->password);
$this->_identity->authenticate();
3、調用Yii::app()->user->login()保存數據(session)
調用YII組件設置session
Yii::app()->user->login($this->_identity,$duration);//$duration,session過期時間,此方法在/framework/web/auth/CWebUser.php LINE 222
$this->_identity對象中getId(),getName()方法一般返回用戶名,用戶ID等,
官方的CUserIdentity類里,都是返回用戶名($this->username)//此方法在/framework/web/auth/CUserIdentity LINE 78
如果需要UID的話,可以在UserIdentity重寫getId()方法,這樣你在使用yii::app()->user->getId()的時候,調用的就是UID而不是username了。
這樣就可以通過yii::app()->user->getId(),yii::app()->user->getName()訪問SESSION里的用戶數據,
如果還需要放其他數據,在CUserIdentity類里重寫getPersistentStates()方法,然后把你要保存的數據以數據形式return 出來。
這里你就可以通過yii::app()->user->getState('key');這種形式調用,這里的key是getPersistentStates()方法return出來的數組key。
此文說明一個yii用戶驗證的思路,不建議復制文中任何一句代碼。可以在閱讀理解后,自己操作。有基礎功力可以看看/framework/web/auth/CWebUser.php源碼