Something I noticed recently and I'm curious about it.
Example 1: the use of getEvent()
In Mage_Core_Model_Locale
in the setLocale()
method, an event is dispatched:
Mage::dispatchEvent('core_locale_set_locale', array('locale'=>$this));
An observer for this event is bindLocale()
from Mage_Adminhtml_Model_Observer
public function bindLocale($observer)
{
if ($locale=$observer->getEvent()->getLocale()) {
if ($choosedLocale = Mage::getSingleton('adminhtml/session')->getLocale()) {
$locale->setLocaleCode($choosedLocale);
}
}
return $this;
}
So as you can see, to retrieve the locale, we first call getEvent()
on the observer.
Example 2: without getEvent()
In Mage_Wishlist_Block_Customer_Wishlist_Item_Options
in the __construct()
method, an event is dispatched:
Mage::dispatchEvent('product_option_renderer_init', array('block' => $this));
So we agree that the same syntax is used for example 1 and 2.
However, an observer for this second example is initOptionRenderer()
from Mage_Bundle_Model_Observer
public function initOptionRenderer(Varien_Event_Observer $observer)
{
$block = $observer->getBlock();
$block->addOptionsRenderCfg('bundle', 'bundle/catalog_product_configuration');
return $this;
}
And as you can see, to retrieve the block, we don't call getEvent()
on the observer
Question
- Why is the
getEvent()
method called in example #1 ? Or why isgetEvent()
not called in example #2 ? - What's the purpose of the
getEvent()
method ? - Where should one use
getEvent()
and where shouldn't one use it ?
Best Answer
It probably has historical reasons, reaching back beyond the 1.0 release.
The
Varien_Event
object is the logical place to contain parameters for a concrete event, but since Magento passes aVarien_Observer
object to all observer methods, shortcut access the parameters made sense (and it has been there at least since 1.1).I actually don't see any value in two different objects as they are used today.
But it obviously not was planned like that from the beginning. In the method
Mage::addObserver()
, not only the event and observer names and static arguments from the<args>
XML node are set, but also a callback:This way, the observers are able to dispatch themselves, with
$observer->dispatch($event)
. In that case, the observers would not have the event data on themselves and you would need you usegetEvent()
to access it. But the method is not used anywhere, so in practice it does not matter.If you want to practice some software archaeology and dig more, you'll find more dead code that hints on original ideas that never made it into the final product, like the
Varien_Event_Observer_Collection
.