Using Magento Core/Session Model – Guide

event-observersession

I have an observer attached to 'front_init_before' action:

<controller_front_init_before>
    <observers>
        <custom_front_init_before>
            <type>singleton</type>
            <class>Gmod_Custom_Model_Observer</class>
            <method>checkCustomId</method>
         </custom_front_init_before>
     </observers>
</controller_front_init_before>

It checks request string for a parameter and saves it in a session. Code from an Observer.php file:

Mage::getSingleton('core/session')->setCustomId($dealer);

Everything works up to now. Data is saved in the session at this point but when I want to read it from a .phtml file:

$custom_id = Mage::getSingleton('core/session')->getCustomId();

$custom_id is empty. Then, in my Observer.php, directly after setCustomId() I call:

Mage::getSingleton('core/session')->getCustomId();

and the 'get' function in phtml file returns the desired value.

Why get function from .phtml file works only when it's called in the Observer too?

Best Answer

When the controller_front_init_before event is dispatched, the session is not initialized yet. Your call to Mage::getSingleton('core/session') will initialize it, but the session model relies on values from the front controller, like the host name of the requets. Since the front controller is not initialized yet, it might be that you end up with a different session id (tbh, I'd have to look into the implementation details to see what exactly goes wrong)

A possible solution is to use Mage::registry() to save the value globally for the current request, and if you need to persist it in the session, do that at a later point, for example when you retrieve the value or in a different observer.

Related Topic