Answer the question
In order to leave comments, you need to log in
Is it possible to create your own objects of the ViewModel type in ZF3 and put the presentation logic there?
How ideologically correct is it to make your own viewModel classes in order to bring the presentation logic into them and make the templates cleaner?
Like this:
Controller
public function indexAction()
{
$products = new ProductsCollection;
$vm = new ProductsViewModel($products);
return $vm;
}
class ProductsViewModel extends ViewModel
{
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);
}
}
<ul>
<?php foreach ($items as $item): ?>
<li>
<div>
<a href="<?= $this->escapeHtml($item['url']) ?>" class="<?= $item['class'] ?>">
<?= $item['title'] ?>
</a>
</div>
<div>
<?php if ($item['showCartBtn']):?>
<form method="post">
<button type="submit" class="btn btn-primary">
Купить за <?= $item['price'] ?>
</button>
</form>
<?php else:?>
<button type="submit" class="btn">
Нет в продаже
</button>
<?php endif;?>
</div>
</li>
<?php endforeach; ?>
</ul>
Answer the question
In order to leave comments, you need to log in
Not only possible, but also necessary...
When your project grows to chaos, creating separate classes for the view will be the only solution for optimizing views.
A simple project does not require this.
This recipe, by the way, applies to any ZF3 component.
The more difficult - the more you have to split up so as not to drown in the ocean of code.
----------------
One more thing.
You don't need to inherit the view class from the ViewModel.
Why is this?
Just create a class in which you "decorate" the variables for the views.
...and pass variables...
return (new ViewModel())
->setVariables($productsView->getItemsVariables())
;
If it seems that without it it will be worse, then use it. The framework does not limit this.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question