{ Hello Magento 2 }

解决 Magento 2 应用问题,更注重深度挖掘。(ง •̀_•́)ง

0%

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:

1
2
3
4
5
6
7
<block class="Magento\Backend\Block\Template" name="admin.temando.batch.solve">
<arguments>
<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>
</arguments>
</block>

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.

References

Better Blocks: Magento 2 PHP View Models