All Articles

Using ViewModel in Magento 2.2

Using ViewModels in Magento 2.2

Magento 2.2 added concept of ViewModel, offloading features from Block classes into separate ViewModel. Using it is quite simple. This might look like that :

<block class="Vendor\Module\Block\Example" name="example">
  <arguments>
    <argument name="view_model" xsi:type="object">Vendor\Module\ViewModel\Example</argument>
  </arguments>
</block>

New created class could be used as follows :

namespace Vendor\Module\ViewModel;

class Example implements \Magento\Framework\View\Element\Block\ArgumentInterface
{
  public function __construct()
  {

  }

  public function getItems()
  {
    // load here some data from db for example
  }
}

Finally, you can insert the new ViewModel class in your existing PHTML templates as follows :

/** @var \Vendor\Module\ViewModel\Example **/
$viewModel = $block->getViewModel();

$items = $viewModel->getItems();

Published Mar 16, 2019

Magento Certified Developer