CakePHP: get user info in models

2019-03-13 01:26发布

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;
}

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

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?

9条回答
Ridiculous、
2楼-- · 2019-03-13 02:06

Dirtiest way would be to just access the user information in the Session. Least amount of overhead associated with that.

The "proper" way would probably be to instantiate the AuthComponent object, so that it does all the stuff it needs to be fully operational. Much like a death star, the AuthComponent doesn't really work well when not fully setup.

To get a new AC object, in the model:

App::import( 'Component', 'Auth' );
$this->Auth = new AuthComponent();

Now you can use $this->Auth in the model, same as you would in the controller.

查看更多
做个烂人
3楼-- · 2019-03-13 02:09

For CakePHP 3.x this easy component is available: http://cakemanager.org/docs/utils/1.0/components/globalauth/. Direct accessing the Session is not possible because of different SessionKeys.

With the GlobalAuthComponent you can access your user-data everywhere with: Configure::read('GlobalAuth');.

Greetz

Bob

查看更多
forever°为你锁心
4楼-- · 2019-03-13 02:10

None of these solutions work in CakePHP version 3. Anyone know of a way to do this? Right now, I'm completely stepping around the framework by accessing the $_SESSION variable directly from my model.

查看更多
登录 后发表回答