Simple Zend_Layout Example

Zend_Layout is in the trunk now, so here's a super simple MVC example that shows it in action:
Zend_Layout Example_Small.png

This example consists of three view files: the outer layout file, the index action view script and a right hand side bar. The remainder of this post describes the key files. If you just want to poke around with the code, then it's at the bottom, so page down now!

Setting up

This is the directory layout:

Zend_Layout Directory.png

As you can see, it's the standard layout and we have one controller, Index, with one action (also index). For good measure, I've thrown in a view helper to collect the base URL to reference the CSS file and also render into a sidebar.

Let's look at the bootstrap file, index.php, first:

<?php

define('ROOT_DIR'dirname(dirname(__FILE__)));

// Setup path to the Zend Framework files
set_include_path('.'
PATH_SEPARATOR ROOT_DIR.'/lib/'
PATH_SEPARATOR get_include_path()
);

// Register the autoloader
require_once 'Zend/Loader.php';
Zend_Loader::registerAutoload();

// Initialise Zend_Layout's MVC helpers
Zend_Layout::startMvc(array('layoutPath' => ROOT_DIR.'/app/views/layouts'));

// Run!
$frontController Zend_Controller_Front::getInstance();
$frontController->addControllerDirectory(ROOT_DIR.'/app/controllers');
$frontController->throwExceptions(true);
try {
    $frontController->dispatch();
} catch(Exception $e) {
    echo nl2br($e->__toString());
}


This is a standard bootstrap with the exception that we initialise the Zend_Layout using the startMvc() function. This takes an array of options, but the one thing you really need to pass in is the directory to find the layout files. I've chosen app/views/layouts as it makes sense in this case. If you are using modules, then maybe app/layouts would be better.

The controller

The index controller contains two functions: init() to render the sidebar to a named response section for use in the layout and then the indexAction() which just puts some text into the view:

<?php

class IndexController extends Zend_Controller_Action
{
    function init()
    {
        // Render sidebar for every action
        $response $this->getResponse();
        $response->insert('sidebar'$this->view->render('sidebar.phtml')); 
    }

    function indexAction()
    {
        $this->view->pageTitle "Zend Layout Example";

        $this->view->bodyTitle '<h1>Hello World!</h1>';
        $this->view->bodyCopy "<p>Lorem ipsum dolor etc.</p>";
    }
}

Two-step view

The view is now two-step. This means that we split our HTML between multiple files. The first step is to render the "inner" scripts, such as the sidebar and the action specific scripts. Then we render the "outer", layout script which embeds the rendered "inner" scripts.

The "inner" scripts

The action view script, index/index.phtml is trivial as it just needs to display the text relevant to the index action only:

<?php echo $this->bodyTitle ;?>
<?php echo $this->bodyCopy ;?>

(told you it was simple!)

The sidebar.phtml is similarly, just the HTML required for our sidebar:


<h2>Sidebar</h2>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>

Again, nice and easy HTML, for this example at least!

The layout script

The layout script, layout.phtml, ties it all together. It contains the HTML that is common to all pages on our website and uses the special construct <?php echo $this->layout()->content ?> to render a named response segment. Note that the view renderer will render to "content" for the action controller's script.

The layout script looks like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title><?php echo $this->escape($this->pageTitle); ?></title>
    <link rel="stylesheet" href="<?php echo $this->baseUrl(); ?>/main.css" type="text/css">
</head>
<body>
    <div id="content">
        <?php echo $this->layout()->content ?>
    </div>
    <div id="sidebar">
        <?php echo $this->layout()->sidebar?>
    </div>
</body>
</html>

For simplicity, we use the baseUrl view helper to retrieve the base URL from the request (via the Front Controller) and we render our two named response segments (content and sidebar) using the view helper layout() which is provide by Zend_Layout.

Conclusion

That's all there is to it. We could have use the partial() view helper to render the sidebar script and coming soon to a svn tree near you is other useful view helpers such as headScript() and headTitle() which will make the <head> section easier to manage.

Here's a zip file of this project: Zend_Layout_Example.zip(It includes a snapshot of the trunk of the Zend Framework which is why it's 3MB big.)

It works for me, at least.

If you would like to comment on this article, please ping me on twitter.
If your response won't fit into 140 characters, write a blog post and then ping me!