【问题标题】:Custom userIdentity class in yii2yii2 中的自定义 userIdentity 类
【发布时间】:2015-03-06 08:43:04
【问题描述】:

我想根据我的具体要求创建自定义的 userIdentity 类。这里的代码是

<?php
namespace app\models;
use yii\web\IdentityInterface;
use app\models\dbTables\Users;

class UserIdentity implements IdentityInterface{

   const ERROR_USERNAME_INVALID=3;
   const ERROR_PASSWORD_INVALID=4;
   const ERROR_NONE=0;
   public $errorCode;

   private  $_id;
   private  $_email;
   private  $_role;
   private  $_name;

   public  function findIdentityById($id){
       $objUserMdl      = new Users;
       $user            = $objUserMdl::findOne($id);
       $userRole        = $objUserMdl->getUserRole($user->user_id);
       $this->_id       = $user->user_id;
       $this->_email    = $user->email_address;
       $this->_role     = $userRole;
       $this->_name     = $user->full_name;
       return $this;
    }

    public function getId()
    {
       return $this->_id;
    }

    public function getName(){
       return $this->_name;
    }

    public function getEmail(){
       return $this->_email;
    }

    public function getRole(){
       return $this->_role;
    }

    public static function findIdentity($id)
    {
      return self::findIdentityById($id);
    }

    public function getAuthKey()
    {
       throw new NotSupportedException('"getAuthKey" is not implemented.');
    }

    public function validateAuthKey($authKey)
    {
        throw new NotSupportedException('"validateAuthKey" is not implemented.');
    }

    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }



}

?>

基本上我有两个表角色和用户,我想在 yii::$app->user->identity 中设置两个表的特定属性

当我调用上述代码时,findIdentity($id) 函数返回错误,原因很明显,说明我不能在静态函数中调用 $this。如何在函数中设置所需的属性并从中返回 userIdentity 类的实例

【问题讨论】:

    标签: php oop yii2 yii2-user


    【解决方案1】:

    我推荐阅读这个:When to use self over $this? 你真的把 2 弄糊涂了。

       $objUserMdl      = new Users;
       $user            = $objUserMdl::findOne($id);
       $userRole        = $objUserMdl->getUserRole($user->user_id);
    

    你在一个对象上调用 ::,你不能那样做。

    我说删除你所做的并重新开始,它应该比你写的容易得多。需要很长时间才能向您展示如何正确地做到这一点,只需查看 yii2 高级模板,看看他们是如何做到的。您可以使用自己的身份类别并在那里设置任何特殊属性。研究一下 yii2 代码就行了。

    【讨论】:

      猜你喜欢
      • 2015-02-13
      • 1970-01-01
      • 2018-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多