Set Up Identity Problem

In model class LoginForm.php,the default function login reads like this


public function login()

	{

		if($this->_identity===null)

		{

			$this->_identity=new UserIdentity($this->username,$this->password);

			$this->_identity->authenticate();

		}

		if($this->_identity->errorCode===UserIdentity::ERROR_NONE)

		{

			$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days

			Yii::app()->user->login($this->_identity,$duration);

			return true;

		}

		else

			return false;

	}

What is the meaning of deciding whether $_identity exists?


if($this->_identity===null)

I can always set up a new $_identity object without knowing whether it is NULL or not,and it works fine when have my user logined in,so,what is the meaning of that?

Here is my code


	public function login()

	{

			$this->_identity=new UserIdentity($this->email,$this->password);

			if($this->_identity->authenticate())

			{

					$duration=3600*24*30;// 30 days

					Yii::app()->user->login($this->_identity,$duration);

					unset($this->_identity);

					return true;

			}

			else 

			{

				return false;		

			}

	}

because the LoginForm has validation which also can create identity and check if user credentials are valid (check array(‘password’, ‘authenticate’) validation rule). if validation was run earlier - you have already identity created and credentials evaluated so you do not have to do this again (in fact it is just performance tuning as validating credentials can be complex and time-consuming).

In siteController,


public function actionLogin()

...

if($model->validate() && $model->login())

...



The first half of the conditional statement has already created a $_indentity,so $model->login() does not have to create it again,right?Then,what about delete the code in LoginForm.php


                if($this->_identity===null)

                {

                        $this->_identity=new UserIdentity($this->username,$this->password);

                        $this->_identity->authenticate();

                }

Cause $model->validate() always run before $model->login(),so there is no need to judge the existence of $_identity am I right?

I can not find other situation in which validation run after login.

this is part of bulletproof component code - it will work no matter if you called ‘validate()’ before ‘login()’ or not. Those functions are in fact independent and when you call them both in correct order as you should, it will work in efficient way, but it will also work if you forget to call first one after applying some changes in code…

So the answer is: yes, you could delete that part if you are 100% sure you will never use this model calling just login() method without validate(). But I would recommend simply leave it as it is now.