Question

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)

Was it helpful?

Solution

There is only one usecase, where singleton for observers would make sense. Thats when you observe two events which depend on each other and you want to get something during the first one, but process it during the second event. You could also use registry here, but that would be something even more global, so singleton and a protected class variable is a good solution.

In reality this is nearly never happening, but magento 1 and 2 use by default shared=true

The probably reason why singleton is default in magento: micro-optimization! Someone thought it would save sooo much time to not need to create the objects again and again. May be true for some events which are called a few hundred times during a request, may be it is even reasonable to do it as default for the cases of bad usage of events.

OTHER TIPS

Magento by default uses the singleton so it saves resources inside the box. two concurrent process operating needs model as they need store and hold data individually. in singleton the object get volatile as soon as new data has been loaded.

Upfrontly magento 2.0 uses shared objects to utilize.. magento 2.0 has very well written destructors which keeps cleaning memory as soon as the job done!

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top