5

I have a behavior which enables segregation of user data based on the user id stored in the session. In CakePHP 1.3 you could do this:

App::import('Component', 'Session');
$session = new SessionComponent();
$session->read('Auth.User.id');

But in CakePHP 2, you can't instantiate a component like that in a behavior because the Component __construct requires the Controller's ComponentCollection as a parameter.

Is it possible to access a session variable inside a behavior in CakePHP 2? What's the best way to do it?

Adexe Rivera
  • 396
  • 6
  • 12
Brad Koch
  • 16,415
  • 18
  • 102
  • 128

2 Answers2

22

If you look at the SessionComponent code, you will see that it is only a wrapper for the CakeSession class.

So you can do the following:

App::uses('CakeSession', 'Model/Datasource');
$user_id = CakeSession::read('Auth.User.id');
nIcO
  • 4,971
  • 22
  • 36
3

In CakePHP 2.0 you can also simply call the Session-methods via the static CakeSession::method() without having to load anything... ;-)

JD-Robbs
  • 120
  • 6
  • 3
    well, your class should still have the `App::uses('CakeSession', 'Model/Datasource');` statement, though! ;) – mark May 24 '12 at 13:43