问题
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