I know this is going to be very simple but I am new enough to not have
it very clear.
If I wanted to have values/constants and code available in all parts
of the application (views, controllers and models), where should I put
them?
Actually, that’s not such a simple question, because it depends a lot on
the data you want to provide. Typically this type of information is
provided in the session hash. In fact that’s one purpose of the session
hash.
In an object oriented applications global variables are generally
considered evil and should be avoided.
Constants are already available anywhere in your application through the
namespace of the class.
If you had:
class MyClass
MY_CONSTANT = “Whatever”
end
You would access that constant with MyClass::MY_CONSTANT. Notice the
namespace operator “::” used.
And a bonus question, I have noticed that session values are not
available in the models. Is there a reason for that or maybe I am not
smart enough to figure it out?
This is by design. It is, technically, a violation of MVC to make
session variables available in model objects. This would create a tight
coupling between the model and the view/controller. MVC is designed to
prevent that.
Model objects should be reusable apart from their view/controller.
Depending on a session variable in your model would break that
reusability. At least that’s the theory. In practice there are ways
around this, but I wouldn’t personally recommend them unless you have no
other choice.
Generally speaking, if you are feeling the need to access session data
in a model, chances are you’re doing something wrong. A proper
encapsulated and decoupled solution should be sought in those cases.
pepe wrote:
Hello,
I know this is going to be very simple but I am new enough to not have
it very clear.
If I wanted to have values/constants and code available in all parts
of the application (views, controllers and models), where should I put
them?
And a bonus question, I have noticed that session values are not
available in the models. Is there a reason for that or maybe I am not
smart enough to figure it out?
Thank you.
Pepe