What is the correct way of getting a helper in a template file of a custom block?
Magento_Search module there is a block:
<referenceContainer name="header-wrapper"> <block class="Magento\Framework\View\Element\Template" name="top.search" as="topSearch" template="Magento_Search::form.mini.phtml" /> </referenceContainer>
form.mini.phtml template I found this way of getting helper object:
$helper = $this->helper('Magento\Search\Helper\Data');
I read in many tutorials that I should inject an instance of the helper in the constructor
__construct() of the block. This can be found in dozens of Magento template files. But in some templates helpers are retrieved with
Just like in the
top.search block from my example. It is an instance of the generic
Magento\Framework\View\Element\Template class so probably that's why the helper had to be retrieved this way (because we can't inject it in the constructor).
So can I use this
$this->helper(...) method in my custom blocks instead of injecting helpers through constructor? Or is it a bad practice and it should be avoided? It's less code and more convenient.
Where is that
helper method implemented? I couldn't find it in the
Magento\Framework\View\Element\Template class nor in its parent classes.