I am currently invoking the method “xyz” using the objectmanager, however the object manager should not be used in phtml file as mentioned in the Magento 2 documentation. What is the best practice way to create an object of other classes?
1 Answer
Yes, ObjectManager should not use in phtml files, because ObjectManager defeats the purpose of Dependency Injection. The advantage of using ObjectManager is less code to write, but it doesn't follow the Magento 2 Development Processes (does not create a mirror class in the generated folder). So there are multiple way to avoid use objectManager in phtm files is following:
If you need an object of the helper class then use the following:
$helperClassObject = $block->helper('[Vendor]\[Module]\Helper\[Helper Class Name]');
If you need an object of another block class then use the following:
$otherBlockObj= $block->getLayout()->createBlock('[Vendor]\[Module]\Block\[Block Class Name]');
Add Dependency in the construct of Block Class Or viewModel Practics
If we need another class object then Recommended way is to use ViewModel. Just add tag in your xml file.
<block name="your_block_name" class="[Vendor]\[Module]\Block\[Block Class Name]" template="Test_Module::test.phtml">
<arguments>
<argument name="your_view_model_name"
xsi:type="object">[Vendor]\[Module]\ViewModel\ClassName</argument>
</arguments>
</block>
In .phtm file (test.phtml)
$viewModelObject = $block->getData('your_view_model_name');
$viewModelObject->calledViewModelMethodName();