Is it okay to use $this->helper(…) in phtml files?
-
15-04-2021 - |
Question
A question on using $this->helper(...)
in phtml files:
- It returns something like this:
ObjectManager->get(...) (Singleton)
- I'm aware it's bad practice to use Object Manager phtml, but technically it's not using Object Manager directly.
Does this make it okay to use?
After doing some research I see:
Object manager should be used only in factories and then as injected in a constructor. The advantage of using this is less code to write. But this does not make it OK. The fact that this is still used in the core, is because it didn't get refactored yet. I hope it will be.
This is in response to using \Magento\Framework\App\ObjectManager::getInstance()
specifically mind you. For $this->helper()
it appears to be more unclear. Magento does still appear to use this in it's core.
La solution
No use of $this->helper() call is deprecated in you should use a view model instead(even though some core file still uses it) . Even use of $this is discouraged in PHTML , $block should be used.
Using view model is best way https://devdocs.magento.com/guides/v2.4/extension-dev-guide/view-models.html#when-to-use-view-models
You can inject the class you want to use in PHTML and create a public getter method for that class
Magento considers even helpers as anti pattern https://devdocs.magento.com/guides/v2.4/ext-best-practices/extension-coding/common-programming-bp.html#avoid-creating-helper-classes