From 5b36503ca8b7617c6f6a4e12535f41863dcd1705 Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Sat, 16 Nov 2013 19:38:43 +0400 Subject: [PATCH] One less SQL query for login sequence in basic and advanced apps --- apps/advanced/common/models/LoginForm.php | 19 +++++++++++++++++-- apps/basic/models/LoginForm.php | 19 +++++++++++++++++-- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/apps/advanced/common/models/LoginForm.php b/apps/advanced/common/models/LoginForm.php index 30fb39b..3a57085 100644 --- a/apps/advanced/common/models/LoginForm.php +++ b/apps/advanced/common/models/LoginForm.php @@ -13,6 +13,7 @@ class LoginForm extends Model public $username; public $password; public $rememberMe = true; + private $_user; /** * @return array the validation rules. @@ -35,7 +36,7 @@ class LoginForm extends Model */ public function validatePassword() { - $user = User::findByUsername($this->username); + $user = $this->getUserByUsername($this->username); if (!$user || !$user->validatePassword($this->password)) { $this->addError('password', 'Incorrect username or password.'); } @@ -48,11 +49,25 @@ class LoginForm extends Model public function login() { if ($this->validate()) { - $user = User::findByUsername($this->username); + $user = $this->getUserByUsername($this->username); Yii::$app->user->login($user, $this->rememberMe ? 3600*24*30 : 0); return true; } else { return false; } } + + /** + * Finds user by username + * + * @param string $username + * @return User|null + */ + private function getUserByUsername($username) + { + if ($this->_user === null) { + $this->_user = User::findByUsername($username); + } + return $this->_user; + } } diff --git a/apps/basic/models/LoginForm.php b/apps/basic/models/LoginForm.php index ad854a2..b02f83e 100644 --- a/apps/basic/models/LoginForm.php +++ b/apps/basic/models/LoginForm.php @@ -13,6 +13,7 @@ class LoginForm extends Model public $username; public $password; public $rememberMe = true; + private $_user; /** * @return array the validation rules. @@ -35,7 +36,7 @@ class LoginForm extends Model */ public function validatePassword() { - $user = User::findByUsername($this->username); + $user = $this->getUserByUsername($this->username); if (!$user || !$user->validatePassword($this->password)) { $this->addError('password', 'Incorrect username or password.'); } @@ -48,11 +49,25 @@ class LoginForm extends Model public function login() { if ($this->validate()) { - $user = User::findByUsername($this->username); + $user = $this->getUserByUsername($this->username); Yii::$app->user->login($user, $this->rememberMe ? 3600*24*30 : 0); return true; } else { return false; } } + + /** + * Finds user by username + * + * @param string $username + * @return User|null + */ + private function getUserByUsername($username) + { + if ($this->_user === null) { + $this->_user = User::findByUsername($username); + } + return $this->_user; + } }