Getting and Setting Session Variables in Magento

Working in the Magento ecosystem can seem daunting at first. Even experienced PHP programmers have a steep learning curve to work through before they really get the sense that they know what they are doing.

One thing that is very easy to do in regular PHP programming is setting a session variable. All you really have to do is set the variable in $_SESSION and you are good to go. In Magento, you probably could do it this way, but you would probably get this feeling that you are doing it incorrectly (and you would be correct).

Luckily, setting session variables in Magento is only difficult until you see it once, and then it is just as easy as setting the variable in $_SESSION. As long as you know how to set variables on an object, you can set a session variable. Look at the following code:

Mage::getSingleton(‘customer/session’)->setMyCoolSessionValue(“variable”);

This piece of code sets the session variable my_cool_session_value to the value of “variable”. Getting the value back out, all you have to do is replace “set” with “get” and it will return the value.

Leave a Reply

Your email address will not be published. Required fields are marked *