Block’s view model

You will probably aggree that:
Templates should only be about representation, and should not contain business logic.
Magento’s blocks perform or provide business logic for the templates.

One problem with inheriting the template block is the constructor is very large. This makes testing and reusability difcult. The answer to this is using a View Mode.
While the block is responsible for outputting its contents and the view model handles the logic.

For example:

<block class="Magento\Backend\Block\Template" name="admin.temando.batch.solve">
        <argument name="template" xsi:type="string">Temando_Shipping::batch/solve.phtml</argument>
        <argument name="viewModel" xsi:type="object">Temando\Shipping\ViewModel\Batch\BatchDetails</argument>
        <argument name="supportViewModel" xsi:type="object">Temando\Shipping\ViewModel\Account\Support</argument>

Now, you can get your view model by using $viewModel = $block->getData('viewModel'); in your template.

This is because Magento\Framework\View\Element\AbstractBlock extends \Magento\Framework\DataObject.


Better Blocks: Magento 2 PHP View Models


电子邮件地址不会被公开。 必填项已用*标注