I observed that there are more than one session class in Magento, for example, Mage::getModel('core/session'), Mage::getModel('customer/session') and so on. When I want to use session as a storage, which session class should I choose? And Why? I'm just confused.
-
What do you mean "as a storage"? What would you store? – René Höhle Jul 17 '12 at 15:24
-
I mean something where we can save and retrieve data. In development, especially in a user session, it's common to save some data to session and retrieve it in coming interactions, such as wishlist items without users' login. – Jul 18 '12 at 12:10
1 Answers
Magento's code is organized into modules. One of the purposes of a module is to provide namespaces. That is, modules allow one group of developers to write code without fear that their variables, objects, etc. will be accidentally stomped on by another group of developers.
Every module in Magento can have it's own session object. By giving each module it's own session object Magento helps developers avoid name conflicts in the PHP global session variable. For example, the following code
Mage::getModel('core/session')->setData('foo',$someValue);
Mage::getModel('customer/session')->setData('foo',$someOtherValue);
will save both values to the session, even though they have the same key.
As to which session class you should choose — if you're writing your own module you should create your own session class/model, thereby avoiding the above mentioned conflicts.
Practically speaking though, saving things on core/session shouldn't be a problem so long as you namespace your variables in some way.
Mage::getModel('core/session')->setData('my_namespace_foo',$someValue);

- 164,128
- 91
- 395
- 599
-
Thanks! Then again, do instances of different type of session class share a lifetime? Can we specify a value for each instance? – Jul 18 '12 at 12:02
-