app/code/Foo/Bar/ViewModel/Math.php
<?php
// All ViewModels go inside your module's "ViewModel" folder
namespace Foo\Bar\ViewModel;
// All ViewModel's need to implement the ArgumentInterface interface
use Magento\Framework\View\Element\Block\ArgumentInterface;
// Name the ViewModel with the single base name of what it does, ex. "Math"
class Math implements ArgumentInterface
{
// Any function can go here, mainly reserved for that complex PHP logic
public function add($x, $y)
{
return $x + $y;
}
}
app/code/Foo/Bar/view/frontend/layout/default.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<!-- All ViewModels are defined within a layout XML file's body tag -->
<body>
<referenceContainer name="content">
<!-- Within the block node you wish to target... -->
<block name="my.block" template="Foo_Bar::my-block.phtml">
<!-- ...create an arguments node, ... -->
<arguments>
<!--
...with an argument child node. There could be any number of child argument nodes
here, each defining their own ViewModel. The name for each of these ViewModels
should be consistently named. Prefer the usage of NAME_view_model (in snake case).
All ViewModels have the xsi:type attribute assigned to "object" in order to work.
The value for this node is the fully qualified name of the ViewModel class.
-->
<argument name="math_view_model"
xsi:type="object">Foo\Bar\ViewModel\Math</argument>
</arguments>
</block>
</referenceContainer>
</body>
</page>
app/code/Foo/Bar/view/frontend/templates/my-block.phtml
<?php
/**
* Typehint all usages of ViewModels for intellisense support & easier debugging.
* Retrieve the ViewModel with getData, passing in the argument name of the ViewModel as a string.
* For the variable name, take your ViewModel name and camelCase it: math_view_model -> $mathViewModel
*/
/** @var \Foo\Bar\ViewModel\Math $mathViewModel */
$mathViewModel = $block->getData('math_view_model');
?>
<div id="my-block">
<!-- You can then call a function of the ViewModel within your PHTML file -->
<h1>Math: 1 + 1 = <?= $mathViewModel->add(1, 1) ?></h1>
</div>
Visit M.academy to learn much more about Magento, Laravel, PHP, Javascript, & Docker.