Working with View Models
Hyvä themes leverage Magento view models for their reusability and composability, offering a flexible alternative to custom block classes. Traditionally, view models are assigned to template blocks via layout XML.
To streamline this process and reduce XML overhead, Hyvä introduces a simpler solution:
The View Model Registry
In Hyvä themes, the hyva-themes/magento2-theme-module automatically makes a $viewModels variable available in every template, similar to $block and $escaper. This variable allows you to fetch any view model (any class implementing ArgumentInterface) directly.
Example:
<?php
use Hyva\Theme\Model\ViewModelRegistry;
use Hyva\Theme\ViewModel\CurrentProduct;
/** @var ViewModelRegistry $viewModels */
/** @var CurrentProduct $currentProduct */
$currentProduct = $viewModels->require(CurrentProduct::class);
No XML Declaration Needed
You no longer need to declare view models in XML!
For a deeper understanding of ViewModels versus Blocks, refer to: Firegento - Better Blocks: Magento 2 PHP View Models.
View Model Cache Tags
View models frequently supply data for template rendering. To ensure cache tags from entities are included in the FPC cache record's HTTP response, implement Magento\Framework\DataObject\IdentityInterface in your view model.
The required cache tags will then be automatically added to the HTTP response's X-Magento-Tags header.
For more details, see the in-depth documentation.
View Model Cache Tags in ESI Cached Blocks
When a block uses a ttl="..." attribute in layout XML, it's cached by Varnish as an ESI section. If its view model also implements IdentityInterface, cache tags might be added to both the full page cache and the ESI cache record.
To ensure cache tags are *only* added to the ESI cache record, pass the $block variable as a second argument to the $viewModels->require() method. This allows the view model registry to detect if it's rendered within an ESI section.
Conditional $block Argument
Only specify the $block argument for view models with cache tags that are used within templates rendered in an ESI section.
In the default Hyvä theme, this applies specifically to the top menu block templates: Magento_Theme/templates/html/header/menu/desktop.phtml and Magento_Theme/templates/html/header/menu/mobile.phtml.
Avoid passing the $block argument unnecessarily.