I’ve been working a lot lately with the Zend Framework for a project at work, and in a recent upgrade from 0.8.0 Preview to 0.9.1 Beta, I made a few discoveries that I’d like to share, especially since the manual for the Zend Framework is sorely out of date, and many of the examples are either deprecated or no longer work.
Most notably, I’ve started using the “new way” of using views, which is still undocumented in the manual. Rather than create a new Zend_View object, tell it where my views are, and echo a call to its
render() method, I’m letting the controller’s
render() method do it all for me. To do this, you need to follow a specific directory structure. For example, if your application is set up like this:
Then, to make use of the controller’s default
render() behavior, add a
scripts/ directory under the
application/views/ directory. Then, inside the
scripts/ directory, create a directory for every controller. The directory must have an all-lowercase version of the controller name without the word “Controller.” So, if you have a
CustomerController class, then the directory would simply be
Inside this directory, create a view file for every action you will render following the same naming conventions. Thus, if you have an
indexAction() and an
addressAction() you would have the files
.phtml extension is the default for views in the Zend Framework; see Rob Allen’s discussion on the use of the
Finally, to use the views, you’ll need to initialize them in your controller. Do this by creating an
init() method and calling
$this->initView() from within it. This sets up the default view for your controller. From within any action, you may now set properties on your view as normal with
$this->view->propertyName and you can render the view with
$this->render() (there is no longer a need to
So, to recap, with a directory structure like this…
…and a controller like this…
…you can much more easily work with views in the Zend Framework.
Zend_Controller_Action::initView() determines the location of the views directory on its own, so you don’t have to tell the application where your views are stored. It determines the location based on the controller directory specified for the current module in use. In this case, we’re using the “default” module, and I’ve specified the controllers directory in my front controller as
/path/to/application/controllers/. The Zend Framework also supports the use of different modules using different controller directories, but I’ll talk more about that later as I share more of my Zend Framework discoveries.