While we can write Class in .phtml itself, then why we need to go to Block. I'm not sure whether the module works without Block or not can anyone answer me with an explanation.

Thank you in Advance

  • 1
    you can override only phtml file, no need to override block just add phtml file in your theme with relevant path, Thats it :) Mar 9 '20 at 6:03
  • You d'ont neef to overide the block. Mar 9 '20 at 7:41

Magento 2 has its own unique architecture which is close to MVVM architecture, where:

M represents Model which is responsible for business logic and data fetch from database.

V stands for View, which is basically frontend (template) part.

VM stands for ViewModel, which is the block object and it acts as a bridge which provides data to the view part for rendering.

To answer one of your question, yes a module can work without a Block class.

To answer second part, if you write your class directly in .phtml file, it might work but that is against the best practice of Magento's architecture.

Magento 2 usage the concept of dependency injection (DI), which basically means, if you want some data from a Model class A, you can inject the Model A in __construct() function of of your block but you cannot use dependency injection pattern in your template directly. You will have to use new keyword or object manager to instantiate any class which is against the dependency pattern used in Magento.

It is best practice to have only html code in .phtml file, and prepare dynamic data in the block and call them from .phtml file for rendering.

If you look at the Single Responsibility Principle (SRP) of SOLID coding principle, it says each class should ideally have only one purpose and the ViewModel concept makes our code SRP compliant.

You can read more about above mentioned concepts using below link:

  1. Magento 2 is use MVC or MVMM?
  2. ViewModels in Magento 2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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