Reputation: 1933
So, I like CakePHP and use it lots. When 2.0 came out, I was pleased to see the AuthComponent be made available throughout your whole application as a static class, which makes lots of things much easier - i.e. you no longer have to pass user data as an argument to model methods.
Recently on a project, I have perceived the need to access methods of the SessionComponent from a Model. Specifically, when a user logs in, some checks are performed to see if the user has a valid subscription to the site. This is all done in the model. If the user no longer has a valid subscription, there are a few reasons why that might be. It seems easiest to return false
from the model, and at the same time set a flash message giving the reason for the expired subscription. Rather than return an array something like this:
array('status' => 0, 'message' => 'You\'re not welcome here anymore')
which needs interpreting in the controller.
There are other times I have wanted to deal with sessions in models, but this is the example that came to mind.
So, I'd like to know, am I right in wanting to access the SessionComponent in models? Should I just use $_SESSION directly when I have this need? Or am I doing things wrong - are there better ways to code?
Upvotes: 2
Views: 920
Reputation: 1
You can write and read data in session in model by using Authcomponent
and session
App::uses('AuthComponent', 'Controller/Component');
App::import('Component', 'Session');
and you can write and read data using following functions
CakeSession::write('Auth.User.id', '1');
debug(CakeSession::read());
Upvotes: 0
Reputation: 14175
Passing session control to the Model violates MVC. You should use the model to make the decisions and the controller to reflect those decisions to the application. In a correct MVC enviroment the Model won't even know you are using sessions much less manipulating it.
Also, using the $_SESSION var violates the framework encapsulation. If you find yourself needing to do that, yes, you went wrong somewhere.
Upvotes: 1
Reputation: 7525
According to CakePHP cookbook:
Usage of the $_SESSION is generally avoided in CakePHP, and instead usage of the Session classes is preferred.
There are several different configurations where you can store session data, f.ex. in the database. So, by using CakeSession
changes to session configuration will not affect every place where you access session data.
I would advice not to use SessionComponent from the model. Better pass parameters to the model with necessary data. Take a look at Understanding Model-View-Controller.
Upvotes: 1
Reputation: 21743
you can always use
CakeSession::read()
anywhere in your application. so also in the model. see previous posts like Reading a session variable inside a behavior in cakephp 2
but be adviced, that you should try to avoid it if possible. models are supposed to be as stateless as possible - mixing them with sessions makes that more and more blurry.
Upvotes: 2