Skip to main content

Generating ZF2 template maps on the fly

19 Aug 2014
Tags: grunt zf2

One of the performance boosters in Zend Framework 2 is using `template_map` instead of the `template_path_stack` in the view manager. While developing, it is easier to use the stack. This is because you don't have to add a mapping every time you create a new view. At the end of the development you might forget to transform the stack into a template map. This is why it is useful to never use the stack and automate the generation of the template_map array instead.

There is already a great tool called `templatemap_generator.php` included in the bin folder of zf2. It can be used to generate a template map for every module in your application. In the next step, we want to make sure that this tool is called every time a view file is created. This kind of automation can be done with a task manager like `Grunt`.

Sample configuration

grunt.initConfig({

    phplint: {
      applicationViews: ['module/Application/**/*.phtml'],
    }

    watch: {
      applicationViews: {
        files: ['module/Application/view/**/*.phtml'],
        tasks: ['phplint:applicationViews', 'exec:generate_application_template_map']
      }
    },

    exec: {
      generate_application_template_map: {
        cmd: '../../vendor/bin/templatemap_generator.php',
        cwd: 'module/Application'
      }
    }

});

grunt.registerTask('generate-template-maps', ['exec:template_map_application']);

By using this configuration, Grunt will watch for file changes in the `view` folder of the `Application` module. When a file has changed, PHPLint will check for syntax errors and finally a new template map file will be generated. There is also a command named `generate-template-maps` which you can run manually.

Note: Make sure to include the npm packages grunt-exec and grunt-phplint.

Conclusion

By automating all of the boring tasks, you can gain a lot of time during development. If you want to automate some more tasks during PHP development, you can check an earlier blog called `Validating your PHP code on the fly`.

whois VeeWee

Selfie

Hi there!

Glad you made it to my blog. Please feel free to take a look around. You will find some interesting stuff, mostly about web development and PHP.

Still can't get enough of me? Quick! Take a look at my Speakerdeck, Twitter, PHPC.Social, or Github account.