So Magento offers 2 ways of declaring an observer. Singleton and Model (new instance) by specifying the <type>
tag in Magento 1.x and by specifying the shared
attribute in Magento 2.
Magento 1 way of doing it.
<events>
<event_name>
<observers>
<unique_observer_name>
<type>model|object|singleton|null</type>
<class>class/alias_here</class>
<method>methdNameHere</method>
</unique_observer_name>
</observers>
</event_name>
</events>
Magento 2 version:
<event name="event_name">
<observer name="unique_observer_name" instance="Class\Name\Here" method="methodNameHere" shared="true|false" />
</event>
So in the case of Magento 1, if the <type>
tag is model or object, the class will be instantiated with Mage::getModel()
. If it's singleton
or it's missing it is instantiated using Mage::getSingleton()
.
In the case of Magento 2, if shared
is false
then the class is instantiated using $this->_observerFactory->create()
(new instance).
if shared
is true it is instantiated using $this->_observerFactory->get()
(singleton).
Between the two versions the event observer idea is very similar, but most of the observers in Magento 1 are used as singletons, because the type
tag is missing and in Magento 2 most (I think all) of the observers have shared="false"
.
I'm puzzled. When should I use singletons and when should I use new instances for observers?
Magento version (1 or 2) is not important here.
A simple use case would do for each approach (new instance or singleton)
type
attribute at all, so that I usually skip it now.type
tag is the same thing as<type>singleton</type>
. So what is the reason we are making observers singletons?