Yii Framework 2.0使用用户数据库登录

O C*_*nor 15 php database login yii yii2

我一直在尝试在互联网上搜索如何在Yii框架2.0中编写代码,以便用户可以使用存储在数据库中的凭据登录,而不是从数组中登录,前缀为models/User.php.我知道如何在Yii 1中做到这一点.但是在Yii 2.0中,我真的不知道该怎么做.由于Yii 2.0还没有发布(只有测试版可用),我在互联网上找不到很多关于使用数据库登录的Yii 2.0教程.

小智 30

您可以使用extesions像实现数据库用户管理https://github.com/amnah/yii2-user.

要么

如果要编写自己的自定义脚本来管理用户,可以覆盖Yii2 identityClass.

在配置的组件部分添加:

'user' => [
        'identityClass'   => 'app\models\User',
        'enableAutoLogin' => true,
    ],
Run Code Online (Sandbox Code Playgroud)

请注意,您的用户模型必须是IMPLEMENT\yii\web\IdentityInterface

以下是可用于实现数据库身份验证的模型类示例

namespace app\models;

//app\models\gii\Users is the model generated using Gii from users table

use app\models\gii\Users as DbUser;

class User extends \yii\base\Object implements \yii\web\IdentityInterface {

public $id;
public $username;
public $password;
public $authKey;
public $accessToken;
public $email;
public $phone_number;
public $user_type;

/**
 * @inheritdoc
 */
public static function findIdentity($id) {
    $dbUser = DbUser::find()
            ->where([
                "id" => $id
            ])
            ->one();
    if (!count($dbUser)) {
        return null;
    }
    return new static($dbUser);
}

/**
 * @inheritdoc
 */
public static function findIdentityByAccessToken($token, $userType = null) {

    $dbUser = DbUser::find()
            ->where(["accessToken" => $token])
            ->one();
    if (!count($dbUser)) {
        return null;
    }
    return new static($dbUser);
}

/**
 * Finds user by username
 *
 * @param  string      $username
 * @return static|null
 */
public static function findByUsername($username) {
    $dbUser = DbUser::find()
            ->where([
                "username" => $username
            ])
            ->one();
    if (!count($dbUser)) {
        return null;
    }
    return new static($dbUser);
}

/**
 * @inheritdoc
 */
public function getId() {
    return $this->id;
}

/**
 * @inheritdoc
 */
public function getAuthKey() {
    return $this->authKey;
}

/**
 * @inheritdoc
 */
public function validateAuthKey($authKey) {
    return $this->authKey === $authKey;
}

/**
 * Validates password
 *
 * @param  string  $password password to validate
 * @return boolean if password provided is valid for current user
 */
public function validatePassword($password) {
    return $this->password === $password;
}

}
Run Code Online (Sandbox Code Playgroud)

我希望这会对你有所帮助.干杯:)