Previous Next

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 int 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 int 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:

// we assume you already have $cache

$id = 'myBigLoop'; // cache id of "what we want to cache"

if (!($data = $cache->load($id))) {
    // cache miss

    $data = '';
    for ($i = 0; $i < 10000; $i++) {
        $data = $data . $i;
    }

    $cache->save($data);

}

// [...] 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:

// make sure you use unique identifiers:
$id1 = 'foo';
$id2 = 'bar';

// block 1
if (!($data = $cache->load($id1))) {
    // cache missed

    $data = '';
    for ($i=0;$i<10000;$i++) {
        $data = $data . $i;
    }

    $cache->save($data);

}
echo($data);

// this isn't affected by caching
echo('NEVER CACHED! ');

// block 2
if (!($data = $cache->load($id2))) {
    // cache missed

    $data = '';
    for ($i=0;$i<10000;$i++) {
        $data = $data . '!';
    }

    $cache->save($data);

}
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.

// the compact construction
// (not good if you cache empty strings and/or booleans)
if (!($data = $cache->load($id))) {

    // cache missed

    // [...] we make $data

    $cache->save($data);

}

// we do something with $data

// [...]

// the complete construction (works in any case)
if (!($cache->test($id))) {

    // cache missed

    // [...] we make $data

    $cache->save($data);

} else {

    // cache hit

    $data = $cache->load($id);

}

// 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:

// if it is a cache miss, output buffering is triggered
if (!($cache->start('mypage'))) {

    // output everything as usual
    echo 'Hello world! ';
    echo 'This is cached ('.time().') ';

    $cache->end(); // output buffering ends

}

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:

$cache->call('veryExpensiveFunc', $params);

// $params is an array
// For example to call veryExpensiveFunc(1, 'foo', 'bar') with
// caching, you can use
// $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 :

class Test {

    // Static method
    public static function foobar($param1, $param2) {
        echo "foobar_output($param1, $param2)";
        return "foobar_return($param1, $param2)";
    }

}

// [...]
$frontendOptions = array(
    'cached_entity' => 'Test' // The name of the class
);
// [...]

// The cached call
$result = $cache->foobar('1', '2');

To cache classic method calls :

class Test {

    private $_string = 'hello !';

    public function foobar2($param1, $param2) {
        echo($this->_string);
        echo "foobar2_output($param1, $param2)";
        return "foobar2_return($param1, $param2)";
    }

}

// [...]
$frontendOptions = array(
    'cached_entity' => new Test() // An instance of the class
);
// [...]

// The cached call
$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.

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 (mandatory) string the complete path and name of the master file

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).

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 choosen 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 :

// [...] // require, configuration and factory

$cache->start();
// if the cache is hit, the result is sent to the browser
// and the script stop here

// 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)

/*
 * You should avoid putting too many lines before the cache section.
 * For example, for optimal performances, "require_once" or
 * "Zend_Loader::loadClass" should be after the cache section.
 */

$frontendOptions = array(
   'lifetime' => 7200,
   'debug_header' => true, // for debugging
   'regexps' => array(
       // cache the whole IndexController
       '^/$' => array('cache' => true),

       // cache the whole IndexController
       '^/index/' => array('cache' => true),

       // we don't cache the ArticleController...
       '^/article/' => array('cache' => false),

       // ... but we cache the "view" action of this ArticleController
       '^/article/view/' => array(
           'cache' => true,

           // and we cache even there are some variables in $_POST
           'cache_with_post_variables' => true,

           // but the cache will be dependent on the $_POST array
           'make_id_with_post_variables' => true
       )
   )
);

$backendOptions = array(
    'cache_dir' => '/tmp/'
);

// getting a Zend_Cache_Frontend_Page object
$cache = Zend_Cache::factory('Page',
                             'File',
                             $frontendOptions,
                             $backendOptions);

$cache->start();
// if the cache is hit, the result is sent to the browser and the
// script stop here

// [...] the end of the bootstrap file
// 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.

// [...] // require, configuration and factory

$cache->start();

// [...]

if ($someTest) {
    $cache->cancel();
    // [...]
}

// [...]
Previous Next
Introduction to Zend Framework
Overview
Installation
Zend_Acl
Introduction
Refining Access Controls
Advanced Usage
Zend_Amf
Introduction
Zend_Amf_Server
Zend_Auth
Introduction
Database Table Authentication
Digest Authentication
HTTP Authentication Adapter
LDAP Authentication
Open ID Authentication
Zend_Cache
Introduction
The theory of caching
Zend_Cache frontends
Zend_Cache backends
Zend_Captcha
Introduction
Captcha Operation
Captcha Adapters
Zend_Config
Introduction
Theory of Operation
Zend_Config_Ini
Zend_Config_Xml
Zend_Config_Writer
Zend_Config_Writer
Zend_Console_Getopt
Introduction to Getopt
Declaring Getopt Rules
Fetching Options and Arguments
Configuring Zend_Console_Getopt
Zend_Controller
Zend_Controller Quick Start
Zend_Controller Basics
The Front Controller
The Request Object
The Standard Router
The Dispatcher
Action Controllers
Action Helpers
The Response Object
Plugins
Using a Conventional Modular Directory Structure
MVC Exceptions
Migrating from Previous Versions
Zend_Currency
Introduction to Zend_Currency
How to work with currencies
Migrating from Previous Versions
Zend_Date
Introduction
Theory of Operation
Basic Methods
Zend_Date API Overview
Creation of dates
Constants for General Date Functions
Working examples
Zend_Db
Zend_Db_Adapter
Zend_Db_Statement
Zend_Db_Profiler
Zend_Db_Select
Zend_Db_Table
Zend_Db_Table_Row
Zend_Db_Table_Rowset
Zend_Db_Table Relationships
Zend_Debug
Dumping Variables
Zend_Dojo
Introduction
Zend_Dojo_Data: dojo.data Envelopes
Dojo View Helpers
Dojo Form Elements and Decorators
Zend_Dom
Introduction
Zend_Dom_Query
Zend_Exception
Using Exceptions
Zend_Feed
Introduction
Importing Feeds
Retrieving Feeds from Web Pages
Consuming an RSS Feed
Consuming an Atom Feed
Consuming a Single Atom Entry
Modifying Feed and Entry structures
Custom Feed and Entry Classes
Zend_File
Zend_File_Transfer
Validators for Zend_File_Transfer
Filters for Zend_File_Transfer
Migrating from previous versions
Zend_Filter
Introduction
Standard Filter Classes
Filter Chains
Writing Filters
Zend_Filter_Input
Zend_Filter_Inflector
Zend_Form
Zend_Form
Zend_Form Quick Start
Creating Form Elements Using Zend_Form_Element
Creating Forms Using Zend_Form
Creating Custom Form Markup Using Zend_Form_Decorator
Standard Form Elements Shipped With Zend Framework
Standard Form Decorators Shipped With Zend Framework
Internationalization of Zend_Form
Advanced Zend_Form Usage
Zend_Gdata
Introduction to Gdata
Authenticating with AuthSub
Using the Book Search Data API
Authenticating with ClientLogin
Using Google Calendar
Using Google Documents List Data API
Using Google Health
Using Google Spreadsheets
Using Google Apps Provisioning
Using Google Base
Using Picasa Web Albums
Using the YouTube Data API
Catching Gdata Exceptions
Zend_Http
Zend_Http_Client - Introduction
Zend_Http_Client - Advanced Usage
Zend_Http_Client - Connection Adapters
Zend_Http_Cookie and Zend_Http_CookieJar
Zend_Http_Response
Zend_InfoCard
Introduction
Zend_Json
Introduction
Basic Usage
JSON Objects
XML to JSON conversion
Zend_Json_Server - JSON-RPC server
Zend_Layout
Introduction
Zend_Layout Quick Start
Zend_Layout Configuration Options
Zend_Layout Advanced Usage
Zend_Ldap
Introduction
Zend_Loader
Loading Files and Classes Dynamically
Loading Plugins
Zend_Locale
Introduction
Using Zend_Locale
Normalization and Localization
Working with Dates and Times
Supported locales
Migrating from previous versions
Zend_Log
Overview
Writers
Formatters
Filters
Zend_Mail
Introduction
Sending via SMTP
Sending Multiple Mails per SMTP Connection
Using Different Transports
HTML E-Mail
Attachments
Adding Recipients
Controlling the MIME Boundary
Additional Headers
Character Sets
Encoding
SMTP Authentication
Securing SMTP Transport
Reading Mail Messages
Zend_Measure
Introduction
Creation of Measurements
Outputting measurements
Manipulating Measurements
Types of measurements
Zend_Memory
Overview
Memory Manager
Memory Objects
Zend_Mime
Zend_Mime
Zend_Mime_Message
Zend_Mime_Part
Zend_OpenId
Introduction
Zend_OpenId_Consumer Basics
Zend_OpenId_Provider
Zend_Paginator
Introduction
Usage
Configuration
Advanced usage
Zend_Pdf
Introduction.
Creating and loading PDF documents.
Save changes to the PDF document.
Document pages.
Drawing
Document Info and Metadata.
Zend_Pdf module usage example
Zend_ProgressBar
Zend_ProgressBar
Zend_Registry
Using the Registry
Zend_Rest
Introduction
Zend_Rest_Client
Zend_Rest_Server
Zend_Search_Lucene
Overview
Building Indexes
Searching an Index
Query Language
Query Construction API
Character Set
Extensibility
Interoperating with Java Lucene
Advanced
Best Practices
Zend_Server
Introduction
Zend_Server_Reflection
Zend_Service
Introduction
Zend_Service_Akismet
Zend_Service_Amazon
Zend_Service_Audioscrobbler
Zend_Service_Delicious
Zend_Service_Flickr
Zend_Service_Nirvanix
Zend_Service_ReCaptcha
Zend_Service_Simpy
Introduction
Zend_Service_StrikeIron
Zend_Service_StrikeIron: Bundled Services
Zend_Service_StrikeIron: Advanced Uses
Zend_Service_Technorati
Zend_Service_Twitter
Zend_Service_Yahoo
Zend_Session
Introduction
Basic Usage
Advanced Usage
Global Session Management
Zend_Session_SaveHandler_DbTable
Zend_Soap
Zend_Soap_Server
Zend_Soap_Client
WSDL Accessor
AutoDiscovery
Zend_Test
Introduction
Zend_Test_PHPUnit
Zend_Text
Zend_Text_Figlet
Zend_Text_Table
Zend_TimeSync
Introduction
Working with Zend_TimeSync
Zend_Translate
Introduction
Adapters for Zend_Translate
Using Translation Adapters
Migrating from previous versions
Zend_Uri
Zend_Uri
Zend_Validate
Introduction
Standard Validation Classes
Validator Chains
Writing Validators
Zend_Version
Reading the Zend Framework Version
Zend_View
Introduction
Controller Scripts
View Scripts
View Helpers
Zend_View_Abstract
Zend_Wildfire
Zend_Wildfire
Zend_XmlRpc
Introduction
Zend_XmlRpc_Client
Zend_XmlRpc_Server
Zend Framework Requirements
PHP Version
PHP Extensions
Zend Framework Components
Zend Framework Dependencies
Zend Framework Coding Standard for PHP
Overview
PHP File Formatting
Naming Conventions
Coding Style
Zend Framework Performance Guide
Introduction
Class Loading
Internationalization (i18n) and Localization (l10n)
View Rendering
Copyright Information