Create a Custom Session Namespace With a Model in Magento

It's possible to create a new Session model in your custom modules in Magento

Posted on June 17, 2016 in Magento

First, make sure you have your node configured with a class prefix to use


<config>
    <global>
         <models>
             <myapp>
                  <class>Jeff_Myapp_Model</class>
             </myapp>
         </models>
    </global>
</config>

Once you have this set up, build your model. Just create a file Session.php and put following code in it:


class Jeff_Myapp_Model_Session extends Mage_Core_Model_Session_Abstract {
    public function __construct() {
        $namespace = 'myapp';
        $namespace .= '_' . (Mage::app()->getStore()->getWebsite()->getCode());
        $this->init($namespace);
        Mage::dispatchEvent('myapp_session_init', array('myapp_session')=>$this));
    }
}

The Mage_Core_Model_Session_Abstract model already contains everything we need.

You could set and access session variables using the magic get/set methods


//set the "foo" variable
Mage::getSingleton("myapp/session")->setFoo("bar");
//or
Mage::getSingleton('myapp/session')->setData('foo', 'bar');

//get data 
Mage::getSingleton('myapp/session')->getFoo();
//or
Mage::getSingleton('myapp/session')->getData('foo');


comments powered by Disqus