2

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!

Bob
  • 873
  • 1
  • 8
  • 21

2 Answers2

2

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.

  • Thanks :). The second url could help... Is that how you would do it? – Bob Jan 15 '15 at 18:12
  • 1
    Yes, I would use events from the controller to pass data into the behavior events. That way, the behavior would be safe to use even when using the Table from shells or other places. – José Lorenzo Rodríguez Jan 15 '15 at 19:12
1

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');
}
fitorec
  • 4,257
  • 2
  • 24
  • 18