View Model in Magento 2

What is a View Model in Magento 2?

A View Model in Magento 2 is a class that provides data and business logic to templates (PHTML files) without placing that logic inside blocks.

View Models were introduced to improve separation of concerns by moving logic out of templates and blocks into dedicated classes.

A View Model must implement the ArgumentInterface provided by the Magento framework.

Why use View Models?

View Models provide a cleaner architecture for the presentation layer.

  • Reduces logic inside PHTML templates.
  • Keeps blocks lightweight.
  • Improves code readability.
  • Encourages better separation of concerns.
  • Makes code easier to test and maintain.

When should View Models be used?

View Models should be used when templates require data or logic that does not belong directly in the block.

  • Fetching data from repositories.
  • Formatting data for display.
  • Preparing view-specific logic.

Example: Create a View Model

Suppose we want to display a custom message in a template using a View Model.

1. Create View Model Class

(File: app/code/VendorName/ModuleName/ViewModel/Message.php)




Example: Attach View Model in Layout XML

The View Model must be assigned to a block using layout XML.

(File: app/code/VendorName/ModuleName/view/frontend/layout/example_index_index.xml)




Example: Use View Model in Template

The View Model can be accessed inside the template using the getViewModel() method.

(File: app/code/VendorName/ModuleName/view/frontend/templates/message.phtml)




How View Models Improve Magento Architecture

Using View Models allows developers to separate responsibilities within Magento's MVC structure.

  • Controllers handle requests.
  • Blocks manage layout structure.
  • View Models handle presentation logic.
  • Templates render the final output.

This structure results in cleaner, more maintainable code.

Best Practices for View Models

  • Use View Models for presentation logic.
  • Avoid writing business logic in PHTML templates.
  • Keep blocks lightweight.
  • Use dependency injection in View Models for required services.