Magento 2 ViewModel as per Single Responsibility Principle

Before studying ViewModel feature of Magento 2, let’s understand first SRP.
SRP stands for Single Responsibility Principle, Every class should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class.
In simple words : Each class should ideally have only one purpose to change.
Basically this is a part of SOLID Principle of Software Development

View Model

View model is class that we inject to phtml, so that require and related data could be access from it.
View Model helps us to avoid unnecessary overriding of the block class Magento\Framework\View\Element\Template ‘s constructor

View Model Implementation

To implement the view model, we need to add the argument in block tag in layout having xsi type object as xsi:type=”object”

<block name="custom.block" template="Vendor_Module::<template>.phtml">
<arguments>
<argument name="viewModel" xsi:type="object"><Vendor>\<Module>\ViewModel\Custom</argument>
</arguments>
</block>

Then we need to create the defined class,

To create the view model we need to implement the Argument Interface in defined class.

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

Now let’s create a ViewModel


<?php
/**
* Blogento Software.
*
* PHP version 7.0+
*
* @category  Blogento
* @package   Blogento_Test
* @author    Blogento <support@blogento.com>
* @copyright Blogento Software Private Limited (https://blogento.com)
* @license   Blogento ASL Licence
*/
namespace <Vendor>\<Module>\ViewModel; 
use Magento\Framework\View\Element\Block\ArgumentInterface; 
class Custom implements ArgumentInterface {
// Do some stuff here.
}

To retrieve the view model in phtml file, we can use below to code in phtml


/** @var \Magento\Framework\View\Element\Template $block*/$block->getData(“viewModel);//OR$block->getViewModel();

Why View Model


It benefits us that we don’t need to create the block class and inject the unnecessary Injection of the Dependencies and call parent. However we are giving the single responsibility to the Class.

Happy coding Friends… 🙂

Leave a Comment

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

Scroll to Top