猫咪兔 2012-02-15 12:42:59 3446次浏览 6条回复 0 0 0
class UserIdentity extends CUserIdentity
{
    public function authenticate()
    {
        $username=strtolower($this->username);
        $user=User::model()->find('LOWER(username)=?',array($username));
		
        if($user===null)
            $this->errorCode=self::ERROR_USERNAME_INVALID;                                
      elseif(!$user->validatePassword($this->password))	                                                     $this->errorCode=self::ERROR_PASSWORD_INVALID;
    else {
        $this->_id=$user->id;
        $this->username=$user->username;
        $this->errorCode=self::ERROR_NONE;
}
return $this->errorCode;

这个是components里的UserIdentity.php里的代码, $user=User::model()->find('LOWER(username)=?',array($username)); 那么这里 else if(!$user->validatePassword($this->password)) 的$user为什么能调用validatePassword个方法呢,validatePassword这个方法是User模型里的方法。 这之间有什么关联吗?具体是怎样调用的。请求高手来指教,先谢过了。

  • 回复于 2012-02-15 14:46 举报

    舰长视屏有讲解,方法是User模型里面的自定义的方法!新手先去看看舰长的视频!
    http://www.yiichina.com/topic/4
    视屏二 【25分】 处!

  • 回复于 2012-02-15 15:12 举报

    要是视频里讲了,就不来发贴问了……

  • 回复于 2012-02-15 15:23 举报

    我不习惯看视频,但是Yii的手册讲解的很全面了呀。

    public CActiveRecord find(mixed $condition='', array $params=array ( )) 
    $condition mixed query condition or criteria. If a string, it is treated as query condition (the WHERE clause); If an array, it is treated as the initial values for constructing a CDbCriteria object; Otherwise, it should be an instance of CDbCriteria. 
    $params array parameters to be bound to an SQL statement. This is only used when the first parameter is a string (query condition). In other cases, please use CDbCriteria::params to set parameters. 
    {return} CActiveRecord the record found. Null if no record is found. 
    

    这里讲解的很明确了,返回值类型是AR。因为查询代码直接用的:
    User的model来find的,所以,调用 User models中的自定义方法是没问题的。
    这种调用方法跟C++的虚函数调用原理差不多。父类指针调用子类的虚表中的函数,所以是安全的,也是合理的。

  • 回复于 2012-02-15 15:32 举报

    每个AR实例对应表中的一行数据,那么可以这样理解,每一行数据就是一个AR实例,则$user就可以调用其相应模型里的方法。应该是这样理解吧?

  • 回复于 2012-02-15 15:43 举报

    从手册上的说明来看,你这样理解,我感觉没啥问题。
    我刚接触Yii没几天,所以我没法保证我理解的是否正确~

  • 回复于 2012-02-15 15:54 举报

    十分感谢!

您需要登录后才可以回复。登录 | 立即注册