2012-07-23 57 views
0

我剛剛瞭解到CakePHP,我希望用戶在編輯自己的信息時輸入舊密碼。從CakePHP中的Model獲取用戶信息

在我的模型user.php的

'password_old' => array(
       'match_old_password' => array(
        'rule' => 'matchOldPassword', 
        'message' => 'Wrong password' 
       ), 
       'minlength' => array(
        'rule' => array('minLength', '8'), 
        'message' => 'Minimum 8 characters long' 
       ) 
      ) 

我創建了一個功能matchOldPassword

public function matchOldPassword(){ 
     if($this->data['User']['password_old']==$current_password){ 
      return true; 
     } 
     return false; 
} 

我的問題是,我怎麼可以在模型獲取當前用戶的密碼的價值?我使用CakePHP 2.1。

回答

2

您可以像在控制器中那樣從模型執行數據庫查詢。

所以在您的用戶模型,你可以撥打:

$this->find('first', array('conditions' => array('User.id' => $userId))); 

$this->read(null, $userId); 

當然,你必須從控制器到模型方法傳遞當前用戶ID。 如果您使用Cake提供的Auth組件,您可以撥打$this->Auth->user('id')來檢索當前登錄的用戶的ID(如果這就是「當前用戶」的含義)。 $this->Auth->user()是一種控制器方法,因此不能在模型中使用。你的設置看起來大致是這樣的:

的usermodel方法:

public function getCurrentUserPassword($userId) { 
    $password = ''; 
    $this->recursive = -1; 
    $password = $this->read('password', $userId); 
    return $password; 
} 

UsersController電話:

$userId = $this->Auth->user('id'); 
$this->User->getCurrentUserPassword($userId); 
+0

謝謝,它的工作原理 – hsenhly 2012-07-24 02:01:46