This is both a question and kind of an answer. But I still would love to find a better solution and you may shed a light on this.
When creating an observer in Magento, the method that is responsible for dispatching it and calling the function that has been configured in the observer's declaration in a module's config.xml file is Mage_Core_Model_App::dispatchEvent
.
In this method, there is this codebit which gathers observers information:
foreach ($eventConfig->observers->children() as $obsName=>$obsConfig) {
$observers[$obsName] = array(
'type' => (string)$obsConfig->type,
'model' => $obsConfig->class ? (string)$obsConfig->class : $obsConfig->getClassName(),
'method'=> (string)$obsConfig->method,
'args' => (array)$obsConfig->args,
);
}
This codebit means that one may declare an < args > node in an observer like this:
<events>
<event_to_observe>
<observers>
<observer_name>
<type>singleton</type>
<class>Namespace_Module_Model_ObserverClass</class>
<method>observerMethod</method>
<args>
<arg_name>arg_value</arg_name>
</args>
</observer_name>
</observers>
</event_to_observe>
</events>
Later in the Mage_Core_Model_App::dispatchEvent
, we can find some code that is responsible for calling the observers' methods and passing the $observer
object as argument.
But, if I am correct, no code sets the $observers[$obsName]['args']
value nor to the $event
object, nor to the $observer
object. Result is: the < args > node from the observer declaration is not accessible in the observer's called method (Namespace_Module_Model_ObserverClass::observerMethod
in my previous example).
My first bet was to try to get the < args > node using something like this:
$args = (array) Mage::getConfig()->getXpath('//events/' . $observer->getEvent()->getName() . '/observers/' . $observer->getName() . '/args');
But, how disappointing, the $name
variable (which is also used in Mage_Core_Model_App::dispatchEvent
for the profiler) is also not passed to the $observer
object... So $observer->getName()
is not returning any data.
So I ended up creating a helper method that any oberver method can call in order to retrieve its < args > node. You can find the gist of this helper and how to use it here:
https://gist.github.com/3312869
It would be so easier to have something like this in Mage_Core_Model_App::dispatchEvent
:
$observer->setMethodArgs($obs['args'])
allowing to use $observer->getMethodArgs()
in the observer method...
Or maybe did I miss something that allows us to retrieve the < args > node but I'm not sure as, searching thru the Core code, I didn't find any < args > node meaning that Magento does not use this feature in its Core.
So, now, the question is... do you have an easy and Magento Core way to retrieve < args > from an observer declaration ?