Access session in models

Hi guys,

I have a little problem, i want to access the session in a model.
I have a variable of that model in session and i want to keep my session
update after each modification, and i want to centralize that in the
model.
Do you know how i can do that ?

Thx

Your problem is a bit bigger than you think. In fact, you shouldn’t do
that. Model knows nothing about controller and it is how it supposed
to be.
Just an advice - when you are going to ask question until you learning
something, don’t try to provide abstract explanation, be as specific
as you can.

You can use after filters on your actions or similar methods to ensure
that updates to the model occur after each action. The controller
should call the model method to make any changes. This way the model
can be used with multiple controllers and they are not coupled. Rails
makes this type of best practice a hard boundary by not allowing
models access to controller data except by the controller invoking
model methods. The only other thing you could look into is
observers. They have access to both the controller and model, but are
only invoked when a change occurs to a model they are registered for.

Michael

Both of the above are correct.

An even easier answer to your question is that you should access the
session in your controller, then pass that information into the model
via a method.

HTH,
Kevin S.

Right, and furthermore, the decoupling of Controller and Model really
should be absolute in any MVC system. Think of it this way. If you
yanked the model objects out of the application and dropped them in
another application (hypothetically), would they still work? If they
were coupled with the session object they would not (just to be clear
this hypotheical receiving application has no Session class). Your
MVC breaks down at a fundamental level.

On the other hand it is generally more complicated to decouple
Controller and View (yet not impossible). Most MVC based frameworks
don’t tent to attempt this decoupling. That being said, it is still
good practice to make every effort to decouple even these.

Generally speaking, the Controller is the least reusable component of
the MVC, since they tend to contain most of the code that is specifc
to a particular application. Model objects on the other hand should
be fully reuseable, requiring clear decoupling from the rest of the
application code.