Zend_Cache Frontends

Zend_Cache_Core

Introduction

Zend_Cache_Core is a special frontend because it is the core of the module. It is a generic cache frontend and is extended by other classes.

Note: All frontends inherit from Zend_Cache_Core so that its methods and options (described below) would also be available in other frontends, therefore they won't be documented there.

Available options

These options are passed to the factory method as demonstrated in previous examples.

Core Frontend Options
Option Data Type Default Value Description
caching Boolean TRUE enable / disable caching (can be very useful for the debug of cached scripts)
cache_id_prefix String NULL A prefix for all cache ids, if set to NULL, no cache id prefix will be used. The cache id prefix essentially creates a namespace in the cache, allowing multiple applications or websites to use a shared cache. Each application or website can use a different cache id prefix so specific cache ids can be used more than once.
lifetime Integer 3600 cache lifetime (in seconds), if set to NULL, the cache is valid forever.
logging Boolean FALSE if set to TRUE, logging through Zend_Log is activated (but the system is slower)
write_control Boolean TRUE Enable / disable write control (the cache is read just after writing to detect corrupt entries), enabling write_control will lightly slow the cache writing but not the cache reading (it can detect some corrupt cache files but it's not a perfect control)
automatic_serialization Boolean FALSE Enable / disable automatic serialization, it can be used to save directly datas which aren't strings (but it's slower)
automatic_cleaning_factor Integer 10 Disable / Tune the automatic cleaning process (garbage collector): 0 means no automatic cache cleaning, 1 means systematic cache cleaning and x > 1 means automatic random cleaning 1 times in x write operations.
ignore_user_abort Boolean FALSE if set to TRUE, the core will set the ignore_user_abort PHP flag inside the save() method to avoid cache corruptions in some cases

Examples

An example is given in the manual at the very beginning.

If you store only strings into cache (because with "automatic_serialization" option, it's possible to store some booleans), you can use a more compact construction like:

  1. // we assume you already have $cache
  2.  
  3. $id = 'myBigLoop'; // cache id of "what we want to cache"
  4.  
  5. if ( ($data = $cache->load($id)) === false ) {
  6.     // cache miss
  7.  
  8.     $data = '';
  9.     for ($i = 0; $i < 10000; $i++) {
  10.         $data = $data . $i;
  11.     }
  12.  
  13.     $cache->save($data);
  14.  
  15. }
  16.  
  17. // [...] do something with $data (echo it, pass it on etc.)

If you want to cache multiple blocks or data instances, the idea is the same:

  1. // make sure you use unique identifiers:
  2. $id1 = 'foo';
  3. $id2 = 'bar';
  4.  
  5. // block 1
  6. if ( ($data = $cache->load($id1)) === false ) {
  7.     // cache missed
  8.  
  9.     $data = '';
  10.     for ($i=0;$i<10000;$i++) {
  11.         $data = $data . $i;
  12.     }
  13.  
  14.     $cache->save($data);
  15.  
  16. }
  17. echo($data);
  18.  
  19. // this isn't affected by caching
  20. echo('NEVER CACHED! ');
  21.  
  22. // block 2
  23. if ( ($data = $cache->load($id2)) === false ) {
  24.     // cache missed
  25.  
  26.     $data = '';
  27.     for ($i=0;$i<10000;$i++) {
  28.         $data = $data . '!';
  29.     }
  30.  
  31.     $cache->save($data);
  32.  
  33. }
  34. echo($data);

If you want to cache special values (boolean with "automatic_serialization" option) or empty strings you can't use the compact construction given above. You have to test formally the cache record.

  1. // the compact construction
  2. // (not good if you cache empty strings and/or booleans)
  3. if ( ($data = $cache->load($id)) === false ) {
  4.  
  5.     // cache missed
  6.  
  7.     // [...] we make $data
  8.  
  9.     $cache->save($data);
  10.  
  11. }
  12.  
  13. // we do something with $data
  14.  
  15. // [...]
  16.  
  17. // the complete construction (works in any case)
  18. if (!($cache->test($id))) {
  19.  
  20.     // cache missed
  21.  
  22.     // [...] we make $data
  23.  
  24.     $cache->save($data);
  25.  
  26. } else {
  27.  
  28.     // cache hit
  29.  
  30.     $data = $cache->load($id);
  31.  
  32. }
  33.  
  34. // we do something with $data

Zend_Cache_Frontend_Output

Introduction

Zend_Cache_Frontend_Output is an output-capturing frontend. It utilizes output buffering in PHP to capture everything between its start() and end() methods.

Available Options

This frontend doesn't have any specific options other than those of Zend_Cache_Core.

Examples

An example is given in the manual at the very beginning. Here it is with minor changes:

  1. // if it is a cache miss, output buffering is triggered
  2. if (!($cache->start('mypage'))) {
  3.  
  4.     // output everything as usual
  5.     echo 'Hello world! ';
  6.     echo 'This is cached ('.time().') ';
  7.  
  8.     $cache->end(); // output buffering ends
  9.  
  10. }
  11.  
  12. echo 'This is never cached ('.time().').';

Using this form it is fairly easy to set up output caching in your already working project with little or no code refactoring.

Zend_Cache_Frontend_Function

Introduction

Zend_Cache_Frontend_Function caches the results of function calls. It has a single main method named call() which takes a function name and parameters for the call in an array.

Available Options

Function Frontend Options
Option Data Type Default Value Description
cache_by_default Boolean TRUE if TRUE, function calls will be cached by default
cached_functions Array   function names which will always be cached
non_cached_functions Array   function names which must never be cached

Examples

Using the call() function is the same as using call_user_func_array() in PHP:

  1. $cache->call('veryExpensiveFunc', $params);
  2.  
  3. // $params is an array
  4. // For example to call veryExpensiveFunc(1, 'foo', 'bar') with
  5. // caching, you can use
  6. // $cache->call('veryExpensiveFunc', array(1, 'foo', 'bar'))

Zend_Cache_Frontend_Function is smart enough to cache both the return value of the function and its internal output.

Note: You can pass any built in or user defined function with the exception of array(), echo(), empty(), eval(), exit(), isset(), list(), print() and unset().

Zend_Cache_Frontend_Class

Introduction

Zend_Cache_Frontend_Class is different from Zend_Cache_Frontend_Function because it allows caching of object and static method calls.

Available Options

Class Frontend Options
Option Data Type Default Value Description
cached_entity (required) Mixed   if set to a class name, we will cache an abstract class and will use only static calls; if set to an object, we will cache this object methods
cache_by_default Boolean TRUE if TRUE, calls will be cached by default
cached_methods Array   method names which will always be cached
non_cached_methods Array   method names which must never be cached

Examples

For example, to cache static calls :

  1. class Test {
  2.  
  3.     // Static method
  4.     public static function foobar($param1, $param2) {
  5.         echo "foobar_output($param1, $param2)";
  6.         return "foobar_return($param1, $param2)";
  7.     }
  8.  
  9. }
  10.  
  11. // [...]
  12. $frontendOptions = array(
  13.     'cached_entity' => 'Test' // The name of the class
  14. );
  15. // [...]
  16.  
  17. // The cached call
  18. $result = $cache->foobar('1', '2');

To cache classic method calls :

  1. class Test {
  2.  
  3.     private $_string = 'hello !';
  4.  
  5.     public function foobar2($param1, $param2) {
  6.         echo($this->_string);
  7.         echo "foobar2_output($param1, $param2)";
  8.         return "foobar2_return($param1, $param2)";
  9.     }
  10.  
  11. }
  12.  
  13. // [...]
  14. $frontendOptions = array(
  15.     'cached_entity' => new Test() // An instance of the class
  16. );
  17. // [...]
  18.  
  19. // The cached call
  20. $result = $cache->foobar2('1', '2');

Zend_Cache_Frontend_File

Introduction

Zend_Cache_Frontend_File is a frontend driven by the modification time of a "master file". It's really interesting for examples in configuration or templates issues. It's also possible to use multiple master files.

For instance, you have an XML configuration file which is parsed by a function which returns a "config object" (like with Zend_Config). With Zend_Cache_Frontend_File, you can store the "config object" into cache (to avoid the parsing of the XML config file at each time) but with a sort of strong dependency on the "master file". So, if the XML config file is modified, the cache is immediately invalidated.

Available Options

File Frontend Options
Option Data Type Default Value Description
master_file (deprecated) String '' the complete path and name of the master file
master_files Array array() an array of complete path of master files
master_files_mode String Zend_Cache_Frontend_File::MODE_OR Zend_Cache_Frontend_File::MODE_AND or Zend_Cache_Frontend_File::MODE_OR ; if MODE_AND, then all master files have to be touched to get a cache invalidation if MODE_OR, then a single touched master file is enough to get a cache invalidation
ignore_missing_master_files Boolean FALSE if TRUE, missing master files are ignored silently (an exception is raised else)

Examples

Use of this frontend is the same than of Zend_Cache_Core. There is no need of a specific example - the only thing to do is to define the master_file when using the factory.

Zend_Cache_Frontend_Page

Introduction

Zend_Cache_Frontend_Page is like Zend_Cache_Frontend_Output but designed for a complete page. It's impossible to use Zend_Cache_Frontend_Page for caching only a single block.

On the other hand, the "cache id" is calculated automatically with $_SERVER['REQUEST_URI'] and (depending on options) $_GET, $_POST, $_SESSION, $_COOKIE, $_FILES. More over, you have only one method to call ( start()) because the end() call is fully automatic when the page is ended.

For the moment, it's not implemented but we plan to add a HTTP conditional system to save bandwidth (the system will send a HTTP 304 Not Modified if the cache is hit and if the browser has already the good version).

Note: This frontend operates by registering a callback function to be called when the output buffering it uses is cleaned. In order for this to operate correctly, it must be the final output buffer in the request. To guarantee this, the output buffering used by the Dispatcher must be disabled by calling Zend_Controller_Front's setParam() method, for example, $front->setParam('disableOutputBuffering', true); or adding "resources.frontcontroller.params.disableOutputBuffering = true" to your bootstrap configuration file (assumed INI) if using Zend_Application.

Available Options

Page Frontend Options
Option Data Type Default Value Description
http_conditional Boolean FALSE use the http_conditional system (not implemented for the moment)
debug_header Boolean FALSE if TRUE, a debug text is added before each cached pages
default_options Array array(...see below...) an associative array of default options:
  • (boolean, TRUE by default) cache: cache is on if TRUE

  • (boolean, FALSE by default) cache_with_get_variables: if TRUE, cache is still on even if there are some variables in $_GET array

  • (boolean, FALSE by default) cache_with_post_variables: if TRUE, cache is still on even if there are some variables in $_POST array

  • (boolean, FALSE by default) cache_with_session_variables: if TRUE, cache is still on even if there are some variables in $_SESSION array

  • (boolean, FALSE by default) cache_with_files_variables: if TRUE, cache is still on even if there are some variables in $_FILES array

  • (boolean, FALSE by default) cache_with_cookie_variables: if TRUE, cache is still on even if there are some variables in $_COOKIE array

  • (boolean, TRUE by default) make_id_with_get_variables: if TRUE, the cache id will be dependent of the content of the $_GET array

  • (boolean, TRUE by default) make_id_with_post_variables: if TRUE, the cache id will be dependent of the content of the $_POST array

  • (boolean, TRUE by default) make_id_with_session_variables: if TRUE, the cache id will be dependent of the content of the $_SESSION array

  • (boolean, TRUE by default) make_id_with_files_variables: if TRUE, the cache id will be dependent of the content of the $_FILES array

  • (boolean, TRUE by default) make_id_with_cookie_variables: if TRUE, the cache id will be dependent of the content of the $_COOKIE array

  • (int, FALSE by default) specific_lifetime: if not FALSE, the given lifetime will be used for the chosen regexp

  • (array, array() by default) tags: tags for the cache record

  • (int, NULL by default) priority: priority (if the backend supports it)

regexps Array array() an associative array to set options only for some REQUEST_URI, keys are (PCRE) regexps, values are associative arrays with specific options to set if the regexp matchs on $_SERVER['REQUEST_URI'] (see default_options for the list of available options); if several regexps match the $_SERVER['REQUEST_URI'], only the last one will be used
memorize_headers Array array() an array of strings corresponding to some HTTP headers name. Listed headers will be stored with cache datas and "replayed" when the cache is hit

Examples

Use of Zend_Cache_Frontend_Page is really trivial:

  1. // [...] // require, configuration and factory
  2.  
  3. $cache->start();
  4. // if the cache is hit, the result is sent to the browser
  5. // and the script stop here
  6.  
  7. // rest of the page ...

a more complex example which shows a way to get a centralized cache management in a bootstrap file (for using with Zend_Controller for example)

  1. /*
  2. * You should avoid putting too many lines before the cache section.
  3. * For example, for optimal performances, "require_once" or
  4. * "Zend_Loader::loadClass" should be after the cache section.
  5. */
  6.  
  7. $frontendOptions = array(
  8.    'lifetime' => 7200,
  9.    'debug_header' => true, // for debugging
  10.    'regexps' => array(
  11.        // cache the whole IndexController
  12.        '^/$' => array('cache' => true),
  13.  
  14.        // cache the whole IndexController
  15.        '^/index/' => array('cache' => true),
  16.  
  17.        // we don't cache the ArticleController...
  18.        '^/article/' => array('cache' => false),
  19.  
  20.        // ... but we cache the "view" action of this ArticleController
  21.        '^/article/view/' => array(
  22.            'cache' => true,
  23.  
  24.            // and we cache even there are some variables in $_POST
  25.            'cache_with_post_variables' => true,
  26.  
  27.            // but the cache will be dependent on the $_POST array
  28.            'make_id_with_post_variables' => true
  29.        )
  30.    )
  31. );
  32.  
  33. $backendOptions = array(
  34.     'cache_dir' => '/tmp/'
  35. );
  36.  
  37. // getting a Zend_Cache_Frontend_Page object
  38. $cache = Zend_Cache::factory('Page',
  39.                              'File',
  40.                              $frontendOptions,
  41.                              $backendOptions);
  42.  
  43. $cache->start();
  44. // if the cache is hit, the result is sent to the browser and the
  45. // script stop here
  46.  
  47. // [...] the end of the bootstrap file
  48. // these lines won't be executed if the cache is hit

The Specific Cancel Method

Because of design issues, in some cases (for example when using non HTTP 200 return codes), you could need to cancel the current cache process. So we introduce for this particular frontend, the cancel() method.

  1. // [...] // require, configuration and factory
  2.  
  3. $cache->start();
  4.  
  5. // [...]
  6.  
  7. if ($someTest) {
  8.     $cache->cancel();
  9.     // [...]
  10. }
  11.  
  12. // [...]

Zend_Cache_Frontend_Capture

Introduction

Zend_Cache_Frontend_Capture is like Zend_Cache_Frontend_Output but designed for a complete page. It's impossible to use Zend_Cache_Frontend_Capture for caching only a single block. This class is specifically designed to operate in concert only with the Zend_Cache_Backend_Static backend to assist in caching entire pages of HTML / XML or other content to a physical static file on the local filesystem.

Please refer to the documentation on Zend_Cache_Backend_Static for all use cases pertaining to this class.

Note: This frontend operates by registering a callback function to be called when the output buffering it uses is cleaned. In order for this to operate correctly, it must be the final output buffer in the request. To guarantee this, the output buffering used by the Dispatcher must be disabled by calling Zend_Controller_Front's setParam() method, for example, $front->setParam('disableOutputBuffering', true); or adding "resources.frontcontroller.params.disableOutputBuffering = true" to your bootstrap configuration file (assumed INI) if using Zend_Application.

blog comments powered by Disqus