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


4.15. View Resolver

When Zend Framework has the template name, it only remains to determine the absolute path to the corresponding .phtml file. This is also called the view template resolving. View templates are resolved with the special Zend Framework's class called the view resolver.

In ZF3, there are two view resolvers out of the box: TemplatePathStack and TemplateMapResolver. Both resolvers take a view template name as input, and return path to view template file as output. The template name is usually composed of module name followed by controller name followed by template name, like "application/index/about", "application/index/index". An exception is "layout/layout", which doesn't include module name.

View resolver settings are stored inside of your module.config.php file under the view_manager key:

<?php
return [
    //...
    
    'view_manager' => [
        //...
        
        'template_map' => [
            'layout/layout'           => __DIR__ . '/../view/layout/layout.phtml',
            'application/index/index' => __DIR__ . '/../view/application/index/index.phtml',
            'error/404'               => __DIR__ . '/../view/error/404.phtml',
            'error/index'             => __DIR__ . '/../view/error/index.phtml',
        ],
        'template_path_stack' => [
            __DIR__ . '/../view',
        ],
    ],
];

You can see that template map resolver's settings are stored under the template_map key. By default, there are several "standard" view templates, which are resolved this way: the index page template, the layout template (we will talk about it in Page Appearance and Layout) and error templates (we will talk about them a little bit later). These standard pages are served with this type of resolver, because it is fast.

The template path stack resolver's settings are stored under the template_path_stack key. You can see that this resolver looks for your view scripts under the "view" directory of your module. That's why we could just put about.phtml file under that directory, and ZF will automatically find the template.

The template map resolver and template path stack resolver work in pair. First, the fast template map resolver tries to find the template view in its array map, and if the page is not found, the template path stack resolver is executed.


Top