djsipe.com | Web Development

Update: With the release of Zend_Layout, the need to this sort of workaround has diminished.

It’s no secret that I’m a big fan of the Zend Framework. After fumbling around with a primitive MVC application at work, I was instantly won over by the clean, and intuitive way they implement MVC. Round about version 0.9, the ViewRenderer was introduced. ViewRenderer is, I’d say, 90% useful. It makes certain assumptions about the way you’re using the framework. If you color between the lines it’s a great help.

One thing I almost always have to do is override the way it selects and automatically renders templates based on controller and action names. I typically roll with a single template and load elements into that template. Of course, I could just disable ViewRenderer altogether, but it does do a lot of other things that I find helpful, like initializing the View.

My solution: extend the default Zend_Controller_Action class. There’s only a few things to do:

  1. Disable the auto-render functionality of ViewRenderer
  2. Add a new $_template property to hold the template to render
  3. Render a single template in the postDispatch method

Here’s the code:

require_once "Zend/Controller/Action.php";

class Blink_Controller_Action extends Zend_Controller_Action
{
    protected $_template = "defaultTemplate.phtml";

    public function init()
    {
        $this->_helper->viewRenderer->setNoRender(true);
        parent::init();
    }

    public function postDispatch()
    {
        echo $this->view->render($this->_template);
    }
}

With our new controller action, we can then largely forget about rendering the View. All we have to do is assign values to the View:

require_once "Blink/Controller/Action.php";

class MyController extends Blink_Controller_Action
{
    public function IndexAction ()
    {
        $this->view->myValue = "some value";
        // Assign more values...
        // Do business logic...

        // Optionally, select a new template to render
        $this->_template = "differentTemplate.phtml";
    }
}
Posted in php | 3 Comments »

© 2012 Donald J. Sipe III | Powered by WordPress | RSS Feed