January 12, 2025

How to use ViewModels in Magento 2

January 12, 2025

How to use ViewModels in Magento 2

View Models are a powerful feature in Magento 2 that provide a cleaner way to deliver business logic to templates.

Introduction

In this tutorial, Today I will explain to how to use ViewModel in Magento 2.

View Models are a powerful feature in Magento 2 that provide a cleaner way to deliver business logic to templates. Introduced in Magento 2.2, View Models solve many limitations of traditional block classes and promote better separation of concerns. In this tutorial, we’ll explore how to implement View Models effectively using practical examples.

What are View Models?

View Models are simple PHP classes that implement the \Magento\Framework\View\Element\Block\ArgumentInterface interface. They provide a way to add business logic to templates without extending the \Magento\Framework\View\Element\Template class, resulting in cleaner, more maintainable code.

Advantages of View Models

Practical Implementation

Let’s create a View Model in our MageDip_Helloworld module to display customer information.

Let’s assume that you have already created custom module, if you did not create, you can create simple module by this way.

Step 1: Create the View Model Class

File: app/code/MageDip/Helloworld/ViewModel/ExampleViewModel.php

<?php
namespace MageDip\Helloworld\ViewModel;

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

class ExampleViewModel implements ArgumentInterface
{

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle(): string
    {
        return 'Congratulations! This text is coming from View Model.';
    }
}

Step 2: Update Layout XML

File: app/code/MageDip/Helloworld/view/frontend/layout/helloworld_index_index.xml

Step 3: Create Template File

File: app/code/MageDip/Helloworld/view/frontend/templates/info.phtml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <referenceContainer name="content">
        <!-- magento custom viewmodel -->
        <block class="Magento\Framework\View\Element\Template"
            name="customer.info"
            template="MageDip_Helloworld::info.phtml">
            <arguments>
                <argument name="view_model"
                        xsi:type="object">MageDip\Helloworld\ViewModel\ExampleViewModel</argument>
            </arguments>
        </block>
    </referenceContainer>
</page>
<?php
/** @var \Magento\Framework\View\Element\Template $block */
/** @var \MageDip\Helloworld\ViewModel\ExampleViewModel $viewModel */
$viewModel = $block->getData('view_model');
?>

<div class="view-model-info">
    <?php if ($viewModel->getTitle()): ?>
        <h2><?= $block->escapeHtml($block->getTitle()) ?></h2>
    <?php endif; ?>
</div>

Go to browser and  use URL yourdomain.com/helloworld to see result.

Magento 2 View Model Example

How It Works

  1. The View Model (CustomerInfo.php) contains the business logic and data retrieval methods.
  2. The Layout XML injects the View Model into the block using the arguments node.
  3. The Template accesses the View Model using $block->getData('view_model').

Best Practices

  1. Single Responsibility: Each View Model should focus on a specific functionality.
  2. Type Hinting: Always use type hints in View Model methods for better code quality.
  3. Documentation: Add proper PHPDoc blocks for better code readability.
  4. Dependency Injection: Use constructor injection for dependencies.
  5. Template Access: Use getData('view_model') to access the View Model in templates.

Common Use Cases

  1. Customer data display
  2. Product information
  3. Category listings
  4. Custom form handling
  5. API data integration

Comparison with Block Classes

FeatureView ModelBlock Class
Base ClassImplements InterfaceExtends Template
ResponsibilityBusiness Logic OnlyMixed Concerns
TestingEasierMore Complex
ReusabilityHighLower
MaintenanceSimplerMore Complex

Conclusion

View Models represent a significant improvement in Magento 2’s frontend architecture. They provide a cleaner, more maintainable way to deliver business logic to templates compared to traditional block classes. By following the examples and best practices outlined in this tutorial, you can implement View Models effectively in your Magento 2 projects.

Key Takeaways:

  1. View Models provide better separation of concerns
  2. They are easier to test and maintain
  3. They promote code reusability
  4. They reduce technical debt
  5. They follow SOLID principles better than block classes

Remember to always consider using View Models instead of extending block classes when adding new functionality to your Magento 2 store.

I hope this tutorial is easy to understand about how to use ViewModel in Magento 2. In case, I missed anything, always feel free to leave a comment in this blog, I’ll get back with proper solution.

Thank you for reading this article. Happy Coding!!!

Share on:
Share on:
LinkedIn
Email
Facebook
Reddit
Twitter
WhatsApp
Skype
Print

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment

Recent posts

LogicRays Blogs

Read other latest blogs on technology, trending, Web & Mobile App, E-Commerce related etc.
We recommend
Featured posts

Table of Contents