Chapter 17. Zend_View
Prev |  | Next

## Chapter 17. Zend_View

## 17.1. Introduction

Zend_View is a class for working with the "view" portion of the model-view-controller pattern. That is, it exists to help keep the view script separate from the model and controller scripts. It provides a system of helpers, output filters, and variable escaping.

Zend_View is template system agnostic; you may use PHP as your template language, or create instances of other template systems and manipulate them within your view script.

Essentially, using Zend_View happens in two major steps: 1. Your controller script creates an instance of Zend_View and assigns variables to that instance. 2. The controller tells the Zend_View to render a particular view, thereby handing control over the view script, which generates the view output.

### 17.1.1. Controller Script

As a simple example, let us say your controller has a list of book data that it wants to have rendered by a view. The controller script might look something like this:

    <?php
    // use a model to get the data for book authors and titles.
    $data = array(
        array(
            'author' => 'Hernando de Soto',
            'title' => 'The Mystery of Capitalism'
        ),
        array(
            'author' => 'Henry Hazlitt',
            'title' => 'Economics in One Lesson'
        ),
        array(
            'author' => 'Milton Friedman',
            'title' => 'Free to Choose'
        )
    );

    // now assign the book data to a Zend_View instance
    Zend::loadClass('Zend_View');
    $view = new Zend_View();
    $view->books = $data;

    // and render a view script called "booklist.php"
    echo $view->render('booklist.php');
    ?>

### 17.1.2. View Script

Now we need the associated view script, "booklist.php". This is a PHP script like any other, with one exception: it executes inside the scope of the Zend_View instance, which means that references to $this point to the Zend_View instance properties and methods. (Variables assigned to the instance by the controller are public properties of the Zend_View instance.) Thus, a very basic view script could look like this:

    <?php if ($this->books): ?>

        <!-- A table of some books. -->
        <table>
            <tr>
                <th>Author</th>
                <th>Title</th>
            </tr>

            <?php foreach ($this->books as $key => $val): ?>
            <tr>
                <td><?php echo $this->escape($val['author']) ?></td>
                <td><?php echo $this->escape($val['title']) ?></td>
            </tr>
            <?php endforeach; ?>

        </table>

    <?php else: ?>

        <p>There are no books to display.</p>

    <?php endif; ?>

Note how we use the "escape()" method to apply output escaping to variables.

Prev |  | Next
16.5. Zend_Service_Yahoo | Home | 17.2. Controller Scripts