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 1


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">
        <argument name="your_view_model_name"

In .phtm file (test.phtml)

$viewModelObject = $block->getData('your_view_model_name');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.