basic 如何把user登陆数据更换为从数据库查询出来的数据 [ 2.0 版本 ]
app\models\user.php有如下静态的信息
private static $users = [
'100' => [
'id' => '100',
'username' => 'admin',
'password' => 'admin',
'authKey' => 'test100key',
'accessToken' => '100-token',
],
];
如何换成自己从数据库获取的信息
或者和数据库信息关联
最佳答案
-
借用小黑豆同学的代码,希望可以帮到你。
下面是一个User model,继承了IdentityInterface
接口, 里面有login
验证方法class Users extends \yii\db\ActiveRecord implements IdentityInterface { public $rememberMe = false; public static function tableName() { return 'users'; } public function rules() { return [ [['username', 'email', 'password', 'create_at', 'status'], 'required'], [['create_at'], 'safe'], [['status'], 'integer'], [['username'], 'string', 'max' => 20], [['email'], 'string', 'max' => 40], [['password'], 'string', 'max' => 64], [['auto_key', 'access_token'], 'string', 'max' => 30], [['username', 'email'], 'unique', 'targetAttribute' => ['username', 'email'], 'message' => 'The combination of Username and Email has already been taken.'] ]; } public function attributeLabels() { return [ 'id' => 'ID', 'username' => 'Username', 'email' => 'Email', 'password' => 'Password', 'create_at' => 'Create At', 'status' => 'Status', 'auto_key' => 'Auto Key', 'access_token' => 'Access Token', ]; } public function scenarios() { return [ 'login'=>[ 'username', 'password'], 'register'=>['username', 'password','email'] ]; } public function login() { if( !$this->validate() ) return false; $user = Users::findOne( [ 'username'=>$this->username ] ); if( $user==null ) { return false; } if( $user->password != $this->password ) { return false; } return Yii::$app->user->login($user, $this->rememberMe ? 3600*24*30 : 0); } public function register() { return true; } public static function findIdentity($id) { return static::findOne(['id'=>$id]); } public static function findIdentityByAccessToken($token, $type = null) { return static::findOne(['access_token' => $token]); } public function getId() { return $this->id; } public function getAuthKey() { return $this->auth_key; } public function validateAuthKey($authKey) { return $this->getAuthKey() === $authKey; } }
然后再action里类似的代码如下(举例):
class DefaultController extends Controller { public $layout = 'basic'; public function actionIndex() { if( !Yii::$app->user->isGuest ) { return Yii::$app->getResponse()->redirect('?r=user/main/index'); } else { $model = new Users(); $model->setScenario('login'); if ($model->load(Yii::$app->request->post()) && $model->login()) { return $this->redirect(['/user/main/index']); } else{ return $this->render('login', ['model' => $model]); } } } }
这些代码当时我都看了,没有问题,model里的基本可以直接用,action是举例。
其他 1 个回答
wodrow China
注册时间:2015-04-09
最后登录:7小时前
在线时长:199小时15分
最后登录:7小时前
在线时长:199小时15分
- 粉丝34
- 金钱42695
- 威望120
- 积分45885