Session accessibility in model and behavior

那年仲夏 提交于 2019-12-10 10:39:03

问题


I am working in Cake 3.x and need the logged in users id. In Cake 2.x you were able to get this via the session or the AuthComponent (how dirty)

AuthComponent::user();

But now in Cake 3.x... How am I able to access the Session in a clean way to get the users id?

I've found: http://book.cakephp.org/3.0/en/development/sessions.html But it says it's easy to get the session from Controllers, Components, Views, and more...

EDIT: A very very dirty solution could be to get the $_SESSION variable. CakePHP does not recommend this option... So, I prever another solution :)

Thank you!


回答1:


You will need to manually pass the value or put it available in an object that is globally accessible. Check this plugin to get an idea of how it can be done in a clean way, it is also probable that what this plugin implements is what you were trying to do anyway :)

https://github.com/hmic/cakephp-blame

Edit: I just checked the source code in that plugin and it seems like it changed the approach to one I don't agree with. This other plugin (https://github.com/ceeram/blame) contains the original implementation that I had in mind.

What it does is attaching an event to your models so that the currently logged in user is passed to the table events and can be read by any behavior.




回答2:


You can access to Session using: Cake\Network\Session;

use Cake\Network\Session;

For example:

public function getSessionUser() {
    $session = new Session();
    return $session->read('Auth.User');
}


来源:https://stackoverflow.com/questions/27964511/session-accessibility-in-model-and-behavior

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!