Over a million developers have joined DZone.

Caching your ZF2 merged configuration

DZone's Guide to

Caching your ZF2 merged configuration

· Web Dev Zone
Free Resource

Tips, tricks and tools for creating your own data-driven app, brought to you in partnership with Qlik.

Zend Framework 2's ModuleManager has the ability to cache the merged configuration information for your application. This is very useful as it allows you to separate out your configuration within the config/autoload directory into logical files without worrying about the performance implications of lots of files.

Enabling caching is simply a case of setting these configuration keys in config/application.config.php within the module_listener_options section:

	'module_listener_options' => array(
        'config_cache_enabled'     => true,
        'module_map_cache_enabled' => true,
        'cache_dir'                => 'data/cache/',
		// other keys go here (e.g. module_paths & config_glob_paths)

This then creates the cache files data/cache/module-classmap-cache.php and data/cache/module-config-cache.php and you're done. If you need to regenerate the files, simply delete then.

During development this can be a pain to remember!

We can solve this by only caching when in production. The easiest way to do this is by setting an environment variable in your virtual host. For Apache, use SetEnv; you're on your own for any other web server.

The way I do this is to modify config/application.config.php like this:

use Zend\Stdlib\ArrayUtils;
$config = array(
	// all standard application configuration ...
$localAppConfigFilename = 'config/application.config.' . getenv('APPLICATION_ENV') . '.php';
if (is_readable($localAppConfigFilename)) {
    $config = ArrayUtils::merge($config, require($localAppConfigFilename));
return $config;

I then create a separate configuration file for each environment. For production, I turn on caching:


return array(
    'module_listener_options' => array(
        'config_cache_enabled' => true,
        'module_map_cache_enabled' => true,

and for my local development, I add some development modules:


return array(
    'modules' => array(

This system allows me to have a faster production site and specific modules loaded when developing that make life easier.

Explore data-driven apps with less coding and query writing, brought to you in partnership with Qlik.


Published at DZone with permission of Rob Allen, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}