How to Use View Models in Hyvä Theme for Magento 2

To use View Models Hyvä theme, start by creating a PHP class that manages the data and logic for specific frontend components. This approach separates business logic from the templates, resulting in cleaner and more maintainable code.

  1. app/code/CustomModule/Hyva/ViewModel/CustomViewModel.php
<?php


namespace CustomModule\Hyva\ViewModel;


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


class CustomViewModel implements ArgumentInterface
{

   public function __construct(
       // Add dependencies or services needed here
   ) {
       // Initialize data or inject necessary dependencies
   }

   public function customData() {
       return "Use View Models in Hyvä Theme";
   }

}

After creating your View Model, the next step is to inject it into the block or template where it will be used. This allows you to access the data and logic encapsulated within the View Model directly in your frontend. By injecting the View Model into your template, you maintain a clean separation of concerns, ensuring that your templates focus solely on rendering while the logic remains within the View Model class

Template file

<?php
/** @var \CustomModule\Hyva\ViewModel\YourViewModel $viewModels */

$viewModels = $viewModels->require(CustomModule\Hyva\ViewModel\YourViewModel::class);

//access the View Model's methods
$result = $viewModels->customData();
?>
<p>
   <?= $result ?>
</p>

Output:

use View Models in the Hyvä theme

Leave a Reply

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