ViewModel in Magento 2
The ViewModel is a class that use for written business logic, object creation for the template and then pass required data to the template.
Using the ViewModel in Magento 2, developer can provide separate class to each block for perform any business logic on template and also we can easily maintain and test block for specific template.
Magento 2.2 in first time release ViewModel feature.
Generally before ViewModel feature launched, we were using helpers in phtml file for call additional logic. The Magento 2 latest version does not recommended for use of helpers in template. It is recommended to use view models instead.
In Magento 2, ViewModels are managed in our module’s directory called ViewModel. The location of ViewModel is not specific for ViewModel's directory.
Let's discuss Magento 2 ViewModel with example.
Magento 2: How to Write ViewModel and use in template ?
Step 1. First you need to define ViewModel name in layout's xml file in block for template. You just need to add arguments node in block node of layout's xml. You can add this ViewModel argument either at the time of block creation using <block> or at the time of referring existing block using <referenceBlock>.
In the below example, Test is the view model class of the Mageniks_Alltest module passed as an argument to a block.
<block name="alltestviewmodel" class="Magento\Framework\View\Element\Template" template="Mageniks_Alltest::test.phtml">
<arguments>
<argument name="view_model" xsi:type="object">Mageniks\Alltest\ViewModel\Test</argument>
</arguments>
</block>
In the below example, I have added or define ViewModel class into existing block using <referenceBlock>.
Once you found the block name for template, you can use this reference block name and then you can add ViewModel for that specific template.
<referenceBlock name="block.name"> <arguments>
<argument name="view_model" xsi:type="object">Mageniks\Alltest\ViewModel\Test</argument>
</arguments>
</referenceBlock>
Step 2. Create ViewModel class and write business logic in it.
The viewmodel class implement the interface \Magento\Framework\View\Element\Block\ArgumentInterface.
<?phpnamespace Mageniks\Alltest\ViewModel;
class Test implements \Magento\Framework\View\Element\Block\ArgumentInterface
{
public function getTitle()
{
return 'Hello World';
}
}
Step 3. Now You can access public method of ViewModel and business logic in template.
<?php/** @var $viewModel \Mageniks\Alltest\ViewModel\Test */
$viewModel = $block->getViewModel();
?>
<h1><?= $viewModel->getTitle(); ?></h1>
So this is the way ViewModel display provide the data to template in Magento 2 and display results in front-end.