View helpers

by Naneau

Another post on views today. But this will be a short one. See, I believe not enough focus is put on the usefulness of view helpers. When trying to separate design from logic, I believe that all things that can be removed from a view should be.

View helpers can come in quite nicely there. Say for instance that you have a Zend_Db_Table_Row assigned to your view, but you want to see the “next” item from the database. Maybe you want to do simple pagination, or maybe you just want to provide some kind of link. A simple view helper for such a situation would look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
 * Naneau_View_Helper_Next
 *
 * find the next item for a Zend_Db_Table_Row object
 *
 * @category   Naneau
 * @package    Naneau_View_Helper
 * @copyright  Copyright (c) 2007 Maurice Fonk - http://naneau.nl
 */

class Naneau_View_Helper_Next {

    /**
     * find the next item
     *
     * @param Zend_Db_Table_Row $row the row
     * @param string $order what to order it by
     * @return Zend_Db_Table_Row|bool
     */

    public function next($row, $order = 'id') {
        $table = $row->getTable();
        $rowset = $table->fetchAll($order . ' > ' . $row->$order, $order . ' ASC', 1);
        if ($rowset->valid()) {
            return $rowset->current();
        }
        return false;
    }
}

You could call it from view context with:

1
<?php $next = $this->next($someRow); ?>

or if you’d just wanted to echo the “title” attribute of the next row:

1
<?php echo $this->next($someRow)->title; ?>

If you would try to fetch the row yourself from within view context you would put logic in your view that shouldn’t be there. Also, there would be a high risk of repetition and loss of readability.

Of course, you could just assign the “next” row from your controller. If you are sure that the view will need it, this would be the best way. But in many cases, the border of what’s supposed to happen in a controller and what should happen in a view helper is a bit vague. View helpers give more control to the designer of your views, while leaving the back-end code safely in your own hands.