Understand View Models in Magento's Model View Controller
Want to learn everything about M2?
Quickly learn and reference all Magento programming basics, concepts & patterns, even with no prior experience.
I’ve previously mentioned that Magento's architecture is a MVC, or Model View Controller architecture, but it’s more accurately described as an MVVmC (Model View ViewModel Controller) structure. The View Model provides a way to abstract away complex logic that may make it’s way into the presentation layer.
What are View Models?
View Models in Magento are essentially PHP classes that are used to implement the presentation logic in a dedicated class, separate from Block classes. Most importantly, they keep our Block classes slim by offloading non-UI logic.
In other words, a View Model class lives in an intermediate layer between the Model and the View, helping to manage the data specifically related to the View.
Why View Models?
As you may know, it's considered a bad practice to have PHP logic in view scripts. Prior to Magento 2.2, Blocks were often used for this purpose, running the risk of them getting cluttered and incomprehensible over time. That's where View Models come in.
They offer a way to create clear, logical chunks of code that are easier to follow, debug, and can be kept in separate classes from the Blocks.
View Models are also extremely reusable. Once a View Model is written, it can be used across different View scripts, making them both a powerful and efficient tool to use in the presentation layer.
The role of a View Model
It's important to remember that a View Model does not replace Blocks. The Block is still in charge of rendering the template. The View Model exists to handle the presentation logic to make it more manageable and organized. Essentially, the View Model prepares the data that is then displayed in a template file. One Block can have multiple View Models, and this makes the system more flexible and helps to keep our code modular and less dependent.
Remember, every bit of complexity that we can abstract away will bring us one step closer to creating cleaner, more efficient code. Now, let’s learn how to implement a View Model in a block, so we can then call it from within our template.