How to use Session in Magento

magento, session

Solution

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

Problem

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.

Original source