Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a session variable inside a behavior in cakephp 2

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?

like image 813
Brad Koch Avatar asked Dec 16 '11 02:12

Brad Koch


2 Answers

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');
like image 76
nIcO Avatar answered Sep 30 '22 17:09

nIcO


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

like image 37
JD-Robbs Avatar answered Sep 30 '22 19:09

JD-Robbs