View Models and Rendering Demystified

“View Models and Rendering Demystified” or the View Model is not your burger!

Often beginner Zend Framework 2  (ZF2) developers are confused about  view models and the whole rendering process.  In this article I will try to explain them making an analogy to ordering a burger at a restaurant. Bear in mind that I will use some terms from the ZF2 world and you may need a bit of support from books like “Learn ZF2” or the online manual to understand the explanations better.

Imagine that you went to a restaurant and ordered cheese burger. In ZF2 terms this will mean that your browser made an HTTP request to a ZF2 application and as a path in the URL it had  /order/cheeseBurger. Also you are not in a hurry and want to eat your burger at the restaurant. The HTTP request for this may look like that:

GET /order/cheeseBurger/?takeAway=0

Routing Event

In a real restaurant the person at the desk will check if there is cheese burger in the menu(hopefully he knows that) and if it can be ordered. In ZF2 this means that the router checks the routing rules and tries to map your URL to a valid routing definition.

In the module.config.php file for the Restaurant module you should have something like this:

'routes' => array(
            'ordercheeseburger' => array(
                'type' => 'Zend\Mvc\Router\Http\Literal',
                'options' => array(
                    'route'    => '/order/cheeseBurger',
                    'defaults' => array(
                        'controller' => 'Restaurant\Controller\Order',
                        'action'     => 'cheeseBurger',

Dispatching Event

The restaurant is offering your favorite cheese burger and the person at the desk instructs the kitchen to prepare your cheese burger. In ZF2 this means that from the routing definition the application has found a controller and action that is responsible for preparing cheese burgers. The action knows what recipe (view name) to use and what ingredients( view variables ) to include in order to prepare the cheese burger.  This is where our View Model  (VM) is created. Think of the VM as a box. Outside of the box stays a label saying the recipe name(view name) to be used and inside of the box we have the ingredients( variables) to use. Every ingredient is labeled (view variable name). At that moment we still do not have the burger ready.

After the box (VM) is ready the person at the desk asks you if you want to eat in the restaurant. If you say yes he opens another box and puts your box in it. In the big box he puts a label saying: decoration. In ZF2 one VM (box ) can have multiple children ( other boxes inside of it) or be part of the content of a bigger box.

namespace Restaurant\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class OrderController extends AbstractActionController
   	public function cheeseBurgerAction() 
		$viewModel = new ViewModel();
		          'cheese' => $gourmetFrenchCheese,
		          'meat'  => $mincedSuperbBeef,
		          'onions'=> $sweetOnion 

		if($this->params('takeAway', false)) {
		return $viewModel;

One day in the kitchen came an important person who wanted to optimize the delivery time. He asked all persons working at the front desk to put all orders inside a new box and add a note with the start time when the order was accepted.  In ZF terms this can be a Debug module that adds debug overlay by creating a new view model (box ) and putting the content of the current box inside of it.

public function onBootstrap(MvcEvent $e)
	// Below is how we get access to the service manager
	$serviceManager = $e->getApplication()->getServiceManager();

        // ..
public function addDebugOverlay(MvcEvent $event)
    	$viewModel = $event->getViewModel();
    	$sidebarView = new ViewModel();
    	$sidebarView->addChild($viewModel, 'content');

(See the Learn ZF2 book repository on github)

Rendering Event

Once the person at the kitchen sees that someone ordered cheese burger he tries to apply the recipe instructions and use the ingredients that are given for that burger. He either knows the recipe or looks in cook books to find it. The books are stacked in a pile. The last book to be added is the first book to be read. When he looks in the books he uses the first recipe for cheese burger that he finds.  In ZF2 we have a resolver. The resolver tries to find from the view template name( recipe name)  the actual template file. And it can use either a template map (the cook remembers the recipe) or search for the view template name in a template path stack( multiple stacked cooking books with recipes until he finds the right one).

'view_manager' => array(
    'template_map' => array(
        'layout/layout' => __DIR__ . '/../view/layout/layout.phtml',
     'template_path_stack' => array(
          __DIR__ . '/../view',

One conclusion from the information above is that a fast cook is one who remembers a lot of recipes instead of looking in cooking books for them. In ZF2 application  looking for view template from a template map is much faster than trying to find the template in a template path stack. Which is important for the performance of your application especially when you have a lot of templates. ( In Learn ZF2 you will find detailed explanation in the Performance chapter)

The cook has all the ingredients and the right recipe. He starts opening the boxes until he reaches the innermost one. It contains information about your cheese burger. He cooks your juicy burger. Then he sees that there is a bigger box and he uses that information to add some salad in your plate as a decoration. In ZF2 the rendering process tries to render(cook) the innermost VM(box), and the content from the rendered VM is used in the parent VM. The decoration is stored in the layout template. The rendered content is the result from rendering the outermost VM.

Event Finish

Finally your burger is ready and served to you with a nice decoration. In ZF2 this is the moment where the rendered content is delivered to the browser.

Enjoy 🙂

Updated Code in LearnZF2 Git Repository

We added two small code changes to the official code repository ( The first one is fixing a small typo in the TableGateway service from the User module and the second one is adding better documentation for using the final code with prefilled SQL database.

If you want to test it you can either do

git pull -f

or clone the changed source code in a new location

git clone

How to Prepare for Zend Framework 2 Certification

It seems that during the summer months a lot of Zend Framework 2(ZF2) users are preparing for ZF2 Certification exam. We received couple of questions related to this and we would like to share with you our recommendations and some insider news.

The ZF2 Certification covers the following major topics: Service Manager, Authentication and Authorization, Utility, MVC, Forms, Web Services, Performance, Security, Module Manager, Internationalization, Database and Event Manager. Which is a pretty broad spectrum and will require a lot of time to study thoroughly.

If you want to reduce that time we would recommend you to do the following steps in the same order as given below:

      Read “Learn ZF2” to understand how the different components in ZF2 are working and how to use them. Make sure that you have read all chapters and understood everything. This step is a must. All readers of the book, that we know of, who took the test also passed the exam. Even people that read the book the night before the exam.
      If you plan to take the exam after October, this year. Then read also the ZF2 Study Guide. Zend is working hard on finishing the ZF2 Study Guide and as far as I am allowed to say, it is expected end of September, the latest. We will inform you as soon as it gets published officially.
      Read the online manual for the topics that are not covered in the book: Web Services, Utility, Internationalization. Read also the topics that were covered in the book, but look for tricky details like for example filtered characters in the name of service managers.

That and a bit of luck should be enough to pass the exam and become proud owner of a shiny ZF2 certificate.

Good luck!

Zend Framework 2 on IBM i/AS400

We have a tip for you if you want to run the source code from the book on IBM i / AS400 machine. One of our readers, Sven Weiss, pointed out that the code doesn’t work out of the box on those systems. It is a known issue, caused by the different behavior of the glob PHP function on that platform. The fix is very simple. You have to edit the application config file located at: config/application.config.php and replace these lines

'config_glob_paths' => array(

with those:

'config_glob_paths' => array(
( !defined('GLOB_BRACE') ? getcwd().'/' : '').'config/autoload/{,*.}{global,local}.php',

We will try to provide a solution to the Zend Framework team, so that such a workaround is not needed in the future.

We will be covering new ZF2 topics.

We would like to give you more information about Zend Framework 2 for topics that were not covered in the “Learn ZF2” book. We will post that information as blog posts and eventually as additional content to the future versions of the book.

For that we will need your help. We have set up a survey where you can give your feedback. Slavey Karadzhov, who is internal Zend guy, will choose the best suggestions from your answers and forward them to Matthew, the ZF2 team leaders, for review.

You can take part in the survey by clicking on
this link

Share this link with fellow programmers so that we can get feedback from wider range of people.

New baby in town !

On the 1st of July my daughter Magdalena was born. She and mommy are doing fine, relaxing and preparing to watch the soccer finals in World Cup 2014. I will update this news later on to put some pictures from our baby.

That is also the reason why I was radio silent the last month. But now I have double the energy to continue helping the Zend Framework 2 and the PHP community. Actually there is also something else that I was working recently and you will get soon some more details about it. For now I will give you only one keyword – “cli”.

So visit the site often to keep informed about the new projects and the improvements that we’ve made together with the help of our contributors to the book.

PHP UnConference this weekend in Mallorca, Spain

This week Slavey Karadzhov will be visiting the PHP UnConference in Mallorca, Spain ( If you happen to be there too you can ask him to sign your copy of the “Learn ZF2” book, discuss with him very complicated issues that you have in Zend Framework 2 or ask him to try and present something useful for the ZF2 community as 45 minute session during the conference.

Hint: Look for a guy walking in the conference halls with big green elePHPant. That most probably will be Slavey and he will be giving the elePHPant to some of the attendees later in the conference.elePHPant