What is a ViewModel in Magento 2?

What is a ViewModel?

In Magento 2, a ViewModel is a PHP class that helps you pass data to your .phtml template files. It separates logic from the view layer, keeping your code clean and easy to manage.

Why Do You Need a ViewModel?

Writing business logic directly inside a template file is a bad practice. Magento encourages using ViewModels to:

  • Keep templates focused only on displaying data
  • Move logic to a separate class
  • Improve testability and reusability

Real-Life Example: Pizza Delivery

Imagine you order a pizza:

  • The template is the delivery box – it shows the final pizza
  • The ViewModel is the chef – it prepares the pizza
  • The Block is the restaurant manager – it oversees operations

You don’t want the delivery box cooking your pizza. Let the chef (ViewModel) handle that.

Magento ViewModel Example: Show Customer Name

This example demonstrates how to use a ViewModel in Magento 2 to display the logged-in customer’s name in a template.

1. ViewModel PHP Class (CustomerData.php)

This class fetches the customer name using Magento’s session model.

<?php

namespace Vendor\Module\ViewModel;

use Magento\Framework\View\Element\Block\ArgumentInterface;

class CustomerData implements ArgumentInterface
{
    protected $customerSession;

    public function __construct(
        \Magento\Customer\Model\Session $customerSession
    ) {
        $this->customerSession = $customerSession;
    }

    public function getCustomerName()
    {
        if ($this->customerSession->isLoggedIn()) {
            return $this->customerSession->getCustomer()->getName();
        }
        return "Guest";
    }
}

2. Layout XML (default.xml)

Define the block and pass the ViewModel class to your template using XML layout.

<block class="Magento\Framework\View\Element\Template"
       name="example.customer"
       template="Vendor_Module::customer.phtml">
    <arguments>
        <argument name="view_model" xsi:type="object">Vendor\Module\ViewModel\CustomerData</argument>
    </arguments>
</block>

3. Template File (customer.phtml)

Use the ViewModel in your template to display the customer name.

<?php
/** @var \Vendor\Module\ViewModel\CustomerData $viewModel */
$viewModel = $block->getData('view_model');
?>
<p>Hello, <?= $viewModel->getCustomerName(); ?>!</p>

When to Use a ViewModel

Use a ViewModel when:

  • You want logic outside of `.phtml`
  • You need a clean and testable solution
  • You want to reuse data preparation logic in multiple templates

Summary

This table compares the role of different Magento 2 components in the context of rendering frontend content:

What? Does?
Template Responsible only for displaying HTML. Should contain minimal or no business logic.
Block Used to manage layout structure and heavy logic, but not ideal for injecting dependencies directly into templates.
ViewModel Acts as a bridge between the template and data sources. Best for passing clean, testable data to templates using dependency injection.

Final Tip

Use the viewmodel in Magento like a helper class for your frontend templates. It enhances modularity, improves unit testing capabilities, and keeps your `.phtml` files clean and readable. ViewModels are especially useful when working on scalable Magento 2 modules or developing custom features that require maintainable and professional code architecture.

Interested in learning more? Check out more blogs in Tech Solutions for related insights and tips.