Chapter 4. Zym_Cache

Chapter 4. Zym_Cache

One of the current problems with Zend_Cache is that it does not support setting default options for backends and frontends. Instantiating cache objects from the factory also prevents usage of custom backends and frontends. Zym_Cache attempts to allievate these problems by providing an improved factory class which has the ability to store default configuration options and generate cache objects without developer interaction with config values.

Setting up the factory is simple because it only has to be done once earlier in the application. While configuring the component is recommended, it is not required. If a default backend is not set, it will use Zend_Cache_Backend_File as the backend with default options. In this case, cache files will be stored to the '/tmp'.

Example 4.1. Configuring Zym_Cache

<?php
$config = new Zend_Config(array(
    'default_backend' => 'Apc',
 
    'frontends'       => array(
        'core' => array(
            'automatic_serialization' => true,
            'cache_id_prefix'         => 'MyAppPrefix_'
        )
    ),
 
    'backends'       => array(
        'apc'  => array(
            // Apc has no configuration options
            // so this array is not required;
            // however, we specify it for example
        ),
 
        'file' => array(
            'cache_dir' => '../tmp'
        )
    )
));
 
Zym_Cache::setConfig($config);

Example 4.2. Zym_Cache simple usage

<?php
// Create a Zend_Cache_Core_Function cache object
$cache = Zym_Cache::factory('Function');
 
// Create a Zend_Cache_Core cache object
// Specifying 'Core' is optional since its
// the default param
$cache = Zym_Cache::factory();
 
// Create a custom core object with custom
// backend
// In this instance, any keys here override the default
// config settings applied via Zym_Cache::setConfig();
$fOptions = array('cache_id_prefix' => 'bar_');
$bOptions = array('cache_dir' => '../cache');
$cache = Zym_Cache::factory('Core', 'File', $fOptions, $bOptions);