Returning $this after observer
The core always return $this;
in the context of observer methods - but there doesn't actually appear to be a reason for it.
Tracing back through dispatchEvent()
you'll find the main method that calls observer methods (in ./app/Core/Model/App.php
)
protected function _callObserverMethod($object, $method, $observer)
{
if (method_exists($object, $method)) {
$object->$method($observer);
} elseif (Mage::getIsDeveloperMode()) {
Mage::throwException('Method "'.$method.'" is not defined in "'.get_class($object).'"');
}
return $this;
}
But at no point is the return value ever actually used or referenced to be passed into another observer down the chain.
Perhaps Magento were thinking longer term to use it as some means to retain/pass data within $this
class instance outside of using sessions/registry; or it could have been legacy code that has just stuck.
I can't see a compelling reason to return $this
- but that being said, if they do it in the core, that's what we do.
As a general rule, whatever the core does - we deem best practice. With the exception of the shocking spelling mistakes :)
$this (pun intended) is called a fluent interface. It allows you to call multiple methods within an object without having refer back to a defined variable.
It's just a Magento convention to always return $this
instead of void
(nothing) if a method has no other return value, regardless of it actually being used for a fluent interface anywhere or not.
The advantage is, that you don't need to think about if it's useful or not, and a superfluous fluent interface is better than a missing one. Also, Magento might start using them for observers, even though this is highly unlikely.