Magento 2 – Access Helper Without Constructor Injection

best practicedependency-injectionhelpermagento2

Is there a clean way to initiate and access a custom helper without using the constructor? Currently I instantiate the custom helper using the constructor of the model as shown here as the accepted answer.

This is great in most cases but now I would like to access a helper method on a model that adds a bit of functionality to the product model – extending \Magento\Catalog\Model\Product. It seems a bit overkill to overwrite this constructor so I am wondering if there is an alternative, acceptable way to do this? Can I just grab it directly via the ObjectManager or roll out my own factory like @philwinkle suggested here or is this not recommended?

Best Answer

the clean way to do it is to inject it in the constructor. Exactly what you are trying to avoid.
Also it can work if you instantiate it via objectManager, but this is discouraged. Even if there are classes instantiated via object manager in the core, this is not the recommended way to do it.
I'm not 100% sure, but I think the suggestion you mention from @philwinke is not valid anymore. That was for an older version. A lot has changed since then.
But even so, if you want to instantiate it via a helper factory, you still need to inject the helper factory in the constructor.
My recommendation is to inject it in the constructor, but if you absolutely don't want that, and you have an instance of the object manager available, instantiate it via object manager.