CakePHP:获取模型中的用户信息

And*_*rea 12 authentication cakephp model

我在模型中移动了一些查找代码.

我之前在我的控制器中

$this->Book->Review->find('first', array(
    'conditions' => array(
        'Review.book_id' => $id,
        'Review.user_id' => $this->Auth->user('id')
    )
));
Run Code Online (Sandbox Code Playgroud)

所以在我的评论模型中我放了类似的东西

function own($id) {
    $this->contain();
    $review = $this->find('first', array(
        'conditions' => array(
            'Review.book_id' => $id,
            'Review.user_id' => AuthComponent::user('id')
        )
    ));
    return $review;
}
Run Code Online (Sandbox Code Playgroud)

所以我从模型中静态地调用AuthComponent.我知道我可以为方法AuthComponent :: password()执行此操作,这对验证很有用.但我特别是使用方法AuthComponent :: user()得到错误

致命错误:在第663行的/var/www/MathOnline/cake/libs/controller/components/auth.php中调用非对象的成员函数check()

有没有办法从模型中获取有关当前登录用户的信息?

Arm*_*osh 13

在"app_model.php"(CakePHP 2.x中的"AppModel.php")中创建一个新函数,因此它将在我们的应用程序中的所有模型中可用:

function getCurrentUser() {
  // for CakePHP 1.x:
  App::import('Component','Session');
  $Session = new SessionComponent();

  // for CakePHP 2.x:
  App::uses('CakeSession', 'Model/Datasource');
  $Session = new CakeSession();


  $user = $Session->read('Auth.User');

  return $user;
}
Run Code Online (Sandbox Code Playgroud)

在模型中:

$user = $this->getCurrentUser();
$user_id = $user['id'];
$username = $user['username'];
Run Code Online (Sandbox Code Playgroud)


小智 11

我使用的方式是这样的:

App::import('component', 'CakeSession');        
$thisUserID = CakeSession::read('Auth.User.id');
Run Code Online (Sandbox Code Playgroud)

它看起来工作得很好:-)


dec*_*eze 6

我认为代码很好,并且属于Controller,或者至少它需要从Controller接收id而不是尝试自己获取它们.模型应该只关注从数据存储中获取数据并返回它.它不应该关心如何在应用程序的其余部分或其请求的参数来自何处来处理数据.否则,您将自己画成一个角落,其中ReviewModel只能检索登录用户的数据,这可能并不总是您想要的.

因此,我会使用这样的函数签名:

function findByBookAndUserId($book_id, $user_id) {
    …
}

$this->Review->findByBookAndUserId($id, $this->Auth->user('id'));
Run Code Online (Sandbox Code Playgroud)


har*_*pax 3

马特·库里(Matt Curry)提出了一个很好的解决方案。您可以使用 beforeFilter 回调将当前登录用户的数据存储在 app_controller 中,并稍后使用静态调用访问它。可以在此处找到说明: http://www.pseudocoder.com/archives/2008/10/06/accessing-user-sessions-from-models-or-anywhere-in-cakephp-revealed/


编辑:上面的链接已过时:https ://github.com/mcurry/cakephp_static_user