對Yii2中 yii\web\User的理解,和自建的app\models\User(基礎版),frontend\models\User的應用原理


 

yii\web\User 是一個統稱,為用戶,沒有具體實例,只能管理;

此處以app\models\User為基准;

app\models\User 是映射數據表user的model類,同時也實現接口,yii\web\IdentityInterface,為什么要實現這個接口呢,

是因為在yii\web\User 中的login方法:public function login(IdentityInterface $identity, $duration = 0) 中的$identity 要求的類型就是IdentityInterface。

因此在lognForm中實現登陸的時候最后要調用yii\web\User 的方法,

而yii\web\User是組件components里面配置的, 所以要在其他代碼中會用到Yii::$app->user,當你登陸以后,這個Yii::$app->user的屬性就有值了,

關於 Yii::$app->user 的幾個屬性, 要查看yii\web\User 中的源碼,摘抄一部分如下:

 

* @property string|int $id The unique identifier for the user. If `null`, it means the user is a guest.
* This property is read-only.
* @property IdentityInterface|null $identity The identity object associated with the currently logged-in
* user. `null` is returned if the user is not logged in (not authenticated).
* @property bool $isGuest Whether the current user is a guest. This property is read-only.
* @property string $returnUrl The URL that the user should be redirected to after login. Note that the type
* of this property differs in getter and setter. See [[getReturnUrl()]] and [[setReturnUrl()]] for details.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class User extends Component
{

其中有@property后面的變量就是Yii::$app->user , 可以寫代碼如:

Yii::$app->user->id ,  返回值 整數|null      整數表示登陸后的用戶id ,返回null表示是游客Guest;

Yii::$app->user->identity , 返回值  實現IdentityInterface類型對象|null      實現IdentityInterface接口的為 app\models\User ,因此此處為app\models\User的對象

Yii::$app->user->isGuest , 返回值 true|false   true表示是游客,false表示不是游客 

Yii::$app->user->returnUrl , 返回值  字符串(string)   即跳轉到登陸界面之前的鏈接,(目前是這樣理解,不知道對錯)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM