Reading a session variable inside a behavior in ca

2019-02-10 06:58发布

问题:

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?

回答1:

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');


回答2:

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