1

Magento 2 encourages the usage of view models instead of filling the blocks with business logic.

A view model is an abstraction of the view exposing public properties and commands. It allows developers to offload features and business logic from block classes into separate classes that are easier to maintain, test, and reuse. Use this approach anytime you need to inject functionality into template files and your code does not need to be backwards compatible with Magento 2.1.

Paginating a custom collection is pretty straight forward (ex: how to add pagination on custom collection in Magento 2), but is it possible to make use of the ViewModel approach instead of adding the code into the Block class?

0

The ViewModel is a model that inherits from nothing whereas the block inherits from Magento/Framework/View/Element/Template

  • as a consequence, your block is coupled with the Template model
  • the ViewModel just implements ArgumentInterface and is not coupled with anything

Yet, the latter can have as many dependency injections as your template code will require.

So, the benefit to using ViewModel is to separate logic to be in a dedicated Model rather than the block like you do point it out.

Now, in terms of implementation. If before you were calling $block->getMyMethod(), you then need to move this method from the block to your ViewModel. That is at this point that you might need to add some dependency injections and that is the only time where your code might differ from the Block.

Overall, using ViewModel will enable your code to be less coupled to layout, block responsabilities.

Please find an example I have to illustrate this answer:

<block template="Mbs_PunchHole::resultapi.phtml" />

will become

<block template="Mbs_PunchHole::resultapi.phtml">
    <arguments>
        <argument name="viewModel" xsi:type="object">Mbs\HolePunch\Block\APIResultViewModel</argument>
    </arguments>
</block>

At the top of your template, to use your ViewModel, insert the following line:

<?php $viewModel = $block->getData('viewModel'); ?>

see full code is you need at https://bitbucket.org/magstaging/punchhole/src/master/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.