Magento 2
Create a ViewModel
Free Preview
// 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;
<?xml version="1.0"?>
<page xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <!-- All ViewModels are defined within a layout XML file's body tag -->
        <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, ... -->
                    ...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"
 * 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>
Want to learn more?

Visit to learn much more about Magento, Laravel, PHP, Javascript, & Docker. logo