It’s possible to create a new Session model in all your custom modules in Magento. This will give you a unique session namespace to isolate your session variables from the rest of the framework.

First, make sure you have your <models /> node configured with a class prefix to use.

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

Once you have this set up, build your model. Here’s a simple Session.php model file.

<?php
class Package_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. Access session variables using the magic get/set methods.

// Set the "foo" variable
Mage::getSingleton("myapp/session")->setFoo("bar");
// Same thing
Mage::getSingleton("myapp/session")->setData("foo", "bar");

// Another example. Let's say we want to name our variable "foo_bar"
Mage::getSingleton("myapp/session")->setFooBar("data");
// or
Mage::getSingleton("myapp/session")->setData("foo_bar", "bar");

// Get data the same way
Mage::getSingleton("myapp/session")->getFoo()
// or
Mage::getSingleton("myapp/session")->getData("foo");

Share this article:

If this resonates with you I'd love to help!

I help business with problems like these every day.

Click below to schedule a call.

About The Author

Bryce Hamrick

Facebook Twitter

Bryce Hamrick is an entrepreneur, business & marketing strategist, and product consultant with nearly two decades of experience in industry. Bryce has been a software engineer, product manager, and director of product management for startups as well as large enterprises. He has led teams to bring dozens of products to market and has executed numerous six-figure product launches. Today Bryce and his team focus on leveraging his product execution strategy to help businesses with growth and scale.