A free and open-source book on Zend Framework for beginners

4.7. Variable Containers

After you have retrieved the data from the HTTP request, you would do something with that data (typically you will process the data with your model layer) and return the data from the action method.

You can see that the indexAction() method of the Index controller returns an instance of the ViewModel class. The ViewModel class is some kind of a variable container. All variables passed to its constructor, will be then automatically accessible by the view script.

Let's have some real-life example. We will create another action method in our IndexController class, which we will call the aboutAction(). The "about" action will display the About page of our site. In the action method, we will create two variables containing information about our website, and return the variables for rendering in a view with the help of ViewModel object:

// The "about" action
public function aboutAction() 
    $appName = 'HelloWorld';
    $appDescription = 'A sample application for the Using Zend Framework 3 book';
    // Return variables to view script with the help of
    // ViewModel variable container
    return new ViewModel([
        'appName' => $appName,
        'appDescription' => $appDescription

In lines 4-5, we create the $appName and $appDescription variables. They store our application name and description, respectively.

In lines 9-12, we pass the variables we've created to the constructor of the ViewModel object as an associative array. The array keys define the names of the variables which on return will be accessible to view script.

The ViewModel class provides several methods that you can additionally use to set variables to ViewModel and retrieve variables from it. The table 4.5 provides the methods summary:

Table 4.5. Methods of the ViewModel class
Method name Description
getVariable($name, $default) Returns a variable by name (or default value if the variable does not exist).
setVariable($name, $value) Sets a variable.
setVariables($variables, $overwrite) Sets a group of variables, optionally overwriting the existing ones.
getVariables() Returns all variables as an array.
clearVariables() Removes all variables.