对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)   即跳转到登陆界面之前的链接,(目前是这样理解,不知道对错)

posted @ 2017-05-11 16:00  jerryhe326  阅读(3796)  评论(0编辑  收藏  举报