Instantiating Helpers in Magento 2
I see you came to right solution, just want to summarize.
Constructor injection should be used to retrieve helper (or any other instance) in whatever class you need:
class SomeClass
{
public function __construct(\Magento\Core\Helper\Data $helper)
{
$this->helper = $helper;
}
public function doSmth()
{
$this->helper->someMethod();
}
}
Notice that no phpDoc comments are required, Magento will read constructor signature directly to figure out what dependencies are required.
\Magento\Core\Helper\Factory should be used only in those rare cases when you have to call a lot of multiple helpers, or you don't know exactly which one you need.
Usage of Object Manager directly is strictly discouraged. So please avoid using:
\Magento\Core\Model\ObjectManager::getInstance()
It's there only for serialization/deserialization.
It looks like Magento's encouraging folks to use their new automatic dependency injection system to get helpers and models into objects via the object's constructor.
The short version? If you have an object that's instantiated by the object manager, and decorate a constructor with a PHPDoc , and the parameters has a proper type hint set, the object manager will automatically instantiate the helper (or, I believe, other objects) for you. @param
For example, the following constructor would inject a a core data helper into the object.
/**
* @param \Magento\Core\Helper\Data $coreData
*/
public function __construct(\Magento\Core\Helper\Data $coreData)
{
$this->_coreHelper = $coreData;
}
Apart from all above answers, if you have to use helper in phtml template you can simply do like this:
$this->helper('[Vendor]\[Module]\Helper\[Helper Name]');
I hope it is helpful if somebody didn't know it before ;)