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
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.Sign up to join this community
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
__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: