What is the correct way of getting a helper in a template file of a custom block?
In 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>
In the 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 $this->helper(...)
method.
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).
1.
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.
2.
Where is that helper
method implemented? I couldn't find it in the Magento\Framework\View\Element\Template
class nor in its parent classes.