Search code examples
phpzend-frameworkzend-viewplaceholder

Zend Framework - Reusing view header information across Controller


In Zend Framework, I have a common use case where I need to propagate the same information in the top section of a view across a particular controller.

For example, if I have a "Book" controller, I want to display the summary book information at the top of the page, and have a tabbed interface below the book to display comments, detailed info, etc. Each tab is an action in the books controller. What is the recommended way to propagate the summary information across the views in the controller such that:

  1. I am not continually fetching the summary book information in each action.
  2. I am not repeating information in my views.

I though of using a Zend View Helper, a placeholder, or the action helper ($this->action...) from within the view.

Any suggestions?


Solution

  • Sounds like you'd want to fetch the book information in an init() method on the controller:

    class MyController extends Zend_Controller_Action
    {
         protected $_book;
    
         public function init()
         {
             // get the book data/model, etc
             $book = $this->_getBook();
    
             // if necessary, store the book for use in the actions
             $this->_book = $book;
    
             // store the book in the view
             $this->view->book = $book;
         }
    }
    

    If an action only renders the book info, then you can probably get away with empty action methods, letting the view scripts do their thing.

    The only downside to this is that it gets the book data on every action. So if there are some actions that do not require the book data, then you'd be eating the overhead of fetching it.