Pragmatism in the real world

Some Zend\View examples

With the release of Beta 3 of Zend Framework, we now have a significantly refactored the ZendView component.

One of the changes made is that there is a ViewModel object that is returned from a controller which contains the variables to be used within the view script along with meta information such as the view script to render. The really nice thing about ViewModels is that they can be nested and this is how the layout composes the action view script.

However, we can do many more interesting things than this and I’ve put together a test application with a controller showing some of the things that can be done.

Some examples:

Change the layout in an action:

    public function differentLayoutAction()
        // Use a different layout
        return new ViewModel();

Create another view model at the layout’s level:

    public function addAnotherViewModelToLayoutAction()
        // Use an alternative layout
        $layoutViewModel = $this->layout();

        // add an additional layout to the root view model (layout)
        $sidebar = new ViewModel();
        $layoutViewModel->addChild($sidebar, 'footer');

        return new ViewModel();

I’ve created some other examples too, so I recommend that you grab the code from GitHub and have a play! The code also includes a second module, Simple, which shows how to change the layout for an entire module.

You should also read the manual!