Wednesday, April 15, 2015

ZF2: Cache your application

Step-by-step guide

Enable the Application cache in your ZF2 application:
  1. Open your index.php file
  2. Please below code:
    /** Is development environment or not */
    define('DEVELOPMENT_ENV', (getenv('APP_ENV') === 'development') ? false : true);
  3. Open your public/.htaccess file and place below line at end of the file:
    SetEnv "APP_ENV" "development"
  4. Open your application.config.php file
  5. Please below code in your file after module_path array:
        // An array of paths from which to glob configuration files after
        // modules are loaded. These effectively override configuration
        // provided by modules themselves. Paths may use GLOB_BRACE notation.
        'config_glob_paths' => array(
            'config/autoload/{,*.}{global,local,app}.php',
        ),

        // Whether or not to enable a configuration cache.
        // If enabled, the merged configuration will be cached and used in
        // subsequent requests.
        'config_cache_enabled' => DEVELOPMENT_ENV ? false : true,
      
        // The key used to create the configuration cache file name.
        'config_cache_key' => 'app-config',
      
        // Whether or not to enable a module class map cache.
        // If enabled, creates a module class map cache which will be used
        // by in future requests, to reduce the autoloading process.
        'module_map_cache_enabled' => DEVELOPMENT_ENV ? false : true,
      
        // The key used to create the class map cache file name.
        'module_map_cache_key' => 'module-map',
      
        // The path in which to cache merged configuration.
        'cache_dir' => 'data/cache',
      
        // Whether or not to enable modules dependency checking.
        // Enabled by default, prevents usage of modules that depend on other modules
        // that weren't loaded.
        'check_dependencies' => DEVELOPMENT_ENV ? true : false

        6. Provide full permission to data/cache dir

That's it. Now run your application, after that you will see 2 files will be created inside data/cache dir that contains the
  • your application configuration at single place and  
  • Your all class-map

It improves your application performance.
Suggestion : Please make enable cache configuration at your production/staging servers only, better to disable cache at development server.