A
A
Alexey Sumin2017-12-13 15:39:57
Zend Framework
Alexey Sumin, 2017-12-13 15:39:57

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;
}

viewmodel
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);
    }
}

Sample
<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

2 answer(s)
N
novrm, 2017-12-14
@asumin

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())
        ;

N
Nikita Dergachov, 2017-12-13
@vanillathunder

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 question

Ask a Question

731 491 924 answers to any question