Layouts in Zend Framework

In my previous post in this series we looked at Zend Framework’s routing and Model-View-Controller (MVC) components. In this post we’ll take slight detour and explore Zend_Layout, a component that lets you have a consistent template for the layout of pages throughout your website.

In the past you may have implemented consisted layouts in PHP using “includes” but, as you’ll see, layouts are much easier to manage than “includes”. The primary improvement over “includes” is that you can change the entire layout of your website without editing every single PHP script. This is because the layout decides where the content gets placed instead of each PHP script including the needed partials (e.g. header and footer). This is accomplished through an implementation of the Two Step View pattern.

If you’re using Zend_Tool then you can enable layouts using the command zf enable layout. This will create a layout view script, application/layouts/scripts/layout.phtml, and add the following line to the production section of your application/configs/application.ini file:

resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts/"

Zend_Layout has a front controller plugin that has two main jobs. First, it takes care of rendering the layout for us. Second, it retrieves what are called “named segments” from Zend Framework’s response object and assigns them as variables in your layout. A segment named “default” is assigned to the variable named content. Typically (unless you do something to override this) the “default” segment will contain the output of your individual controller actions. This means that you can render the content of your controller actions wherever you’d like in your layout view script by outputting the value of $this->layout()->content.

In the demo blogging application, Postr, I’ve also created a header layout view script, application/layouts/scripts/header.phtml, and a footer layout view script, application/layouts/scripts/footer.phtml. The header and footer layout view scripts are rendered by outputting the results of $this->render('header.phtml') and $this->render('footer.phtml'), respectively.

In my next post in this series I plan on taking a look at the Entry controller (application/controllers/EntryController.php) in the demo blogging application, Postr. We’ll explore its actions and corresponding view scripts. Zend_Form, Zend_Paginator, and modeling domain objects will be touched on briefly, but explored in more depth in later posts.