Can ZF3 to create your own objects of type ViewModel, and pass there the logic of the presentation?

How ideologically right to make their own viewModel classes to make them in the logic of the ideas and make templates cleaner ?

For example:
Controller
public function indexAction()
{
 $products = new ProductsCollection;
 $vm = new ProductsViewModel($products);
 return $vm;
}


ViewModel
class ProductsViewModel ViewModel extends
{
 public function __construct(ProductsCollection $products)
{
 $items = array();
 foreach ($products as $product) {
 $items[] = [
 'url' => '/product/' . $product['id'],
 'price' => !empty($product['price']) ? \number_format($product['price'], 2, ',', ' ') : ",
 'title' => $product['title'],
 'class' => empty($product['hot price']) ? ": 'active',
 'showCartBtn' => !empty($product['price'])
];
}

 $this->setVariable('items', $items);
}
}


Template
the <ul>
 <?php foreach ($items as $item): ?>
the <li>
the <div>
 <a href="<?= $this->escapeHtml($item['url']) ?>" class="<?= $item['class'] ?>">
 <?= $item['title'] ?>
</a>
</div>
the <div>
 <?php if ($item['showCartBtn']):?>
 <form method="post">
 <button type="submit" class="btn btn-primary">
 Buy now for <?= $item['price'] ?>
</button>
</form>
 <?php else:?>
 <button type="submit" class="btn">
 Sold out
</button>
 <?php endif;?>
</div>
</li>
 <?php endforeach; ?>
</ul>
June 10th 19 at 15:23
2 answers
June 10th 19 at 15:25
Solution
Not only possible, but necessary...
When your project will grow to the chaos - the creation of separate classes to represent will be the only solution to optimize species.
A simple project does not require it.

This recipe, by the way refers to any component ZF3.
The harder - the more you have to split up in order not to drown in the ocean of code.

----------------
One more thing.
You do not need to inherit the view class from the ViewModel.
Why is this?
Just create a class in which "make" variables for types.
... and pass variables...

return (new ViewModel())
->setVariables($productsView->getItemsVariables())
 ;
June 10th 19 at 15:27
If it seems that it will be worse, use. The framework is not limiting.

Find more questions by tags Zend Framework