php的yii框架开发总结4

用户验证的实现:/protected/components/UserIdentity.php

修改:function authenticate()函数中的语句

 1 public function authenticate()
 2     {
 3         $username=strtolower($this->name);
 4         $user=User::model()->find('LOWER(name)=?',array($username));
 5         if($user===null)
 6             $this->errorCode=self::ERROR_USERNAME_INVALID;
 7         else if(!$user->validatePassword($this->password))
 8             $this->errorCode=self::ERROR_PASSWORD_INVALID;
 9         else
10         {
11             $this->_id=$user->id;
12             $this->username=$user->name;
13             $this->errorCode=self::ERROR_NONE;
14         }
15         return $this->errorCode==self::ERROR_NONE;
16     }

第三行代码:strtolower()把名字换成小写,名字不分大小写,这个地方strtolower($this->name),$this->name和$this->username效果是一样的,因为name就是返回的username值,另外$username是变量名,和基类中的username不是一个值,下面的$this->username是指的基类中的值;
第四行代码:因为class User extends CActiveRecord,即User类继承自CActiveRecord基类,所以可以使用CActiveRecord中的属性和方法,其中find()函数,public CActiveRecord find(mixed $condition='', array $params=array ( ))
注意:find()函数查找指定条件的单个活动记录。如果同时满足条件,返回第一个结果,只能返回一条记录,没有满足条件的返回null。
第7行代码validatePassword($password)函数是在User类中定义的方法:

1 public function validatePassword($password)
2     {
3         return $this->password===$password;
4     }
errorCode和username是CUserIdentity基类中的属性,可以直接调用,该基类还有id和name属性,不过是只读的,不能修改。
所以新定义了private $_id;变量,并且override了getID()方法,
基类源代码:
public function getId()
{
    return $this->username;
}

public function getName()
{
    return $this->username;
}
两个方法返回结果是一样的

那么这个函数在哪用到了呢?在protected\models\LoginForm.php文件中用到了:

 1 public function login()
 2     {
 3         if($this->_identity===null)
 4         {
 5             $this->_identity=new UserIdentity($this->username,$this->password);
 6             $this->_identity->authenticate();
 7         }
 8         if($this->_identity->errorCode===UserIdentity::ERROR_NONE)
 9         {
10             $duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days
11             Yii::app()->user->login($this->_identity,$duration);
12             return true;
13         }
14         else
15             return false;
16     }

在该类中定义了private $_identity变量,$this->_identity=new UserIdentity($this->username,$this->password);这条语句是用了UserIdentity类的构造函数创建了一个新类。下面的语句就是调用UserIdentity类中的authenticate()方法然后判断用户信息的正确性了。

posted @ 2013-08-08 16:16  楠楠IT  阅读(262)  评论(0编辑  收藏  举报