Magento 2.3 – Alternatives to $this in Template Logic

coding-standardsmagento2.3

In this https://github.com/magento/magento2/blob/2.3/app/code/Magento/Contact/view/frontend/templates/form.phtml you see something like this

$this->helper('Magento\Contact\Helper\Data')->getUserEmail())

In code quality checks I see $this in templates is now deprecated

What's the recommended approach?

Best Answer

I would say that either extending the block or creating a view model that injects the helper, then exposes proxy methods for the data you want to access would be the correct way to do it.

Using helpers directly in template files is generally frowned upon since you are introducing business logic into the template. This just seems like old ported code from M1, that will be refactored into the new design patterns at some point in the future.

But if you really wanted a function that behaved the same way, you could reimplement it into your block since all the helper function does is load the class through object manager, you can find the implementation here https://github.com/magento/magento2/blob/2.3-develop/lib/internal/Magento/Framework/View/TemplateEngine/Php.php#L120

Related Topic