CakePHP:获取模型中的用户信息 [英] CakePHP: get user info in models

查看:21
本文介绍了CakePHP:获取模型中的用户信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm moving some of my find code inside models.

以前在我的控制器中我有

Previously in my controller I had

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

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

so in my Review model I put something like

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

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

So I'm calling AuthComponent statically from the Model. I know I can do this for the method AuthComponent::password(), which is useful for validation. But I'm getting errors using the method AuthComponent::user(), in particular

致命错误:调用成员函数check() 在一个非对象上/var/www/MathOnline/cake/libs/controller/components/auth.php在线663

Fatal error: Call to a member function check() on a non-object in /var/www/MathOnline/cake/libs/controller/components/auth.php on line 663

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

Is there a way to get the info about the currently logged user from a model?

推荐答案

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

There is a nice solution by Matt Curry. You store the data of the current logged user in the app_controller using the beforeFilter callback and access it later using static calls. A description can be found here: 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

这篇关于CakePHP:获取模型中的用户信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆