4

I'm trying to understand couple of things about helper classes scope and lifetime. I think I got it but it's critical for me to be sure.

So can you please tell me if I'm right about the following assumptions about helper's scope?

  1. a helper is a singleton by default (eg when calling Mage::helper() it's the same as calling getSingleton()).
  2. a singleton only live in the scope of the http request, eg next http request will no longer have those singletons. same rule applies to helpers.
  3. it's possible to use session storage for a helper, which will make the helper instance live through the entire user session, but by default it's not session based.
  4. calling the same helper from different modules (while handling the same request) will return the same instance. eg a helper singleton instance can be used to transfer data between modules? (I'm not asking if it's the right way, just if its possible :))
  5. calling the same helper from different events that are triggered from the same http request will return the same helper instance.
  6. calling helper from cron job callback will always instantiate a new instance (because cron job is equivalent to an http request scope?)

So am I correct about the points above? Can someone confirm it? I did some testing and found some info here and there, but I want to make sure it's the expected defined behavior, and not just random behavior that might change between versions and systems.

4

The helper will only live during the execution, so #2 is true, it will not persist after the request.

#3, sure you can save any data you want from the Helper into core/session, customer/session, checkout/session etc. #4, #5, #6 should return the same result no matter what. Calling the helper from a Model, Controller, even a template file will return the same result.

My only hesitation is on #1. I am not sure if you can consider it a singleton. I would guess it may depend on what its doing. Hopefully this helps.

  • if you are only unsure about #1 its good enough, as long as you are sure about the other points being valid. I'll wait a little longer to see if no one else think otherwise and accept this answer. thanks :) – Ronen Ness Jan 3 '16 at 17:11
4

Everything you wrote is accurate.

To clarify the singleton behavior: both, Mage::helper() and Mage::getSingleton() look up an entry in the Magento registry (which is a global data storage per request) in the form _helper/module/class or _singleton/module/class and if it does not exist, instantiate the helper or singleton and store it in the registry.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.