1

We want to follow the best practice to add additional functionality to a block template without "rewriting" (i.e. a DI preference) the block.

Is there a nice way to inject the main block (which methods we need to access) to a view model ?

We were thinking about the following code inside of the template:

<?php
    $block->getViewModel()->setBlock($block);
?>

But is that the right way to do it?

1

As always, it depends ;)

I‘ve used the approach you describe, but I prefer to use method arguments instead, e.g.

$viewModel->getSomeFoo($block->getProduct());

This decouples the view model from the block.

However, if there are many public methods on the view model and many values from the block are required the setting the block on the view model might be a pragmatic choice.

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.