The use of Zend_cache

Source: Internet
Author: User

First, Zend_cache fast browsing

Zend_cache provides a general way to cache any data.

Caching in the Zend Framework is done by the front-end, while passing through the back-end adapters (File, Sqlite, Memcache ...) and a flexible IDs and tags system (identifier and tag system) store cache records. The core of the module (Zend_cache_core) is universal, flexible, and configurable. For specific needs, here are some of the front ends that inherit from Zend_cache_core: Output, File, Function, and Class.

(1) Call Zend_cache::factory () to get a front-end

$frontendOptions = Array (' LifeTime ' => 7200,//two-hour cache lifetime ' automatic_serialization ' => true); $backendOptions = Array (' Cache_dir ' => './tmp/'//directory of cache files); Get a Zend_cache_core object $cache = Zend_cache:: Factory (' Core ', ' File ', $frontendOptions, $backendOptions) ;

(2) caching the results from the query in the database

Now that you have a front end, you can cache any type of data (a serialization of ' serialization '). For example, caching a result from an expensive database query is possible. The result is cached and no longer needs to be connected to the database, and the data is retrieved and deserialized directly in the cache.

$cache in the previous example already initialized//To see if a cache exists: if (! $result = $cache-> load (' Myresult ')) {//cache not hit, connect to database $db = Zend_ Db:: Factory ([...]); $result = $db-> fetchall (' SELECT * from huge_table '); $cache-> Save ($result, ' myresult ');//Use Zend_cache object cache query Results} else {//cache name, read out cache to $result content in Myresult tag. Echo ' This one ' from cache!\n\n ';} Print_r ($result); (3) output front-end cache output with Zend_cache

By adding conditional logic, we ' mark up ' (mark) those segments that want to cache output (sections), encapsulate these sections between the start () and End () methods (this is similar to the first example, and is the core strategy of caching). In the interior, output your data as usual, when the end () method is executed, all previous outputs are cached. At the next run, the entire segment (the code before the end () method call) is skipped and the data is retrieved directly from the cache (as long as the cached record is valid).

Front-end to set cache storage time and whether to serialize objects $frontendOptions = Array (' LifeTime ' =>,//cache lifeTime of seconds ' automatic _serialization ' => false//This is the default anyway s); The back-end adapter configures the cache's storage path $backendOptions = Array (' Cache_dir ' => './tmp/'); $cache = Zend_cache:: Factory (' Output ', ' File ', $frontendOptions, $backendOptions); Passes a unique identifier to the start () method if (! $cache-> Start (' MyPage ')) {//Output as Usual:echo ' Hello world! ' ; Echo ' This is cached ('. Time (). ' ) ' ; $cache-> End (); The output is saved and sent to the browser} Echo ' This are never cached ('. Time (). ' ). ' ; Summary: The cache identification (passed to save () and start () in the use of Zend_cache is particularly important to note. It must be unique to each resource you cache, otherwise unrelated cache records will overwrite each other and, worse, lead to incorrect display results.

--------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------

second, the principle of caching

Caching principle:

There are three key concepts in Zend_cache.

One is the unique identifier (a string) used to identify the cached record.

The second is the ' lifeTime ' directive, which, as seen in the example, defines the lifetime of the cache record (exceeding that value, and the cache record being destroyed).

The third key concept is conditional execution, and some of your code can be skipped to speed performance. Front-End functions such as. Zend_cache_core::get ()) returns False when the cache is not hit, which enables the user to handle the conditions in the if () {...} statement, including the part of the code that they want to cache (or skip), and finally whether you must save the blocks you have generated (for example: Zend_ Cache_core::save ()).

Note: ' Cache hit ' is a term that means that when a cache record is found to be available, it is valid and is ' fresh ' (in other words, it is not yet expired). Cache Miss ' indicates that caching misses occur when the required data is not found in the cache. When a cache miss occurs, you have to generate your data and make it cached. For a cache hit, the backend automatically retrieves the cached record from the cache.

You must use Zend_cache::factory () to get the front-end instance. Your own directly instantiated front-end or backend does not work as expected.

(1) Zend_cache factory method

We Choose a backend (for example ' File ' or ' Sqlite ' ...) $backendName = ' [...] ' ; Select a front end (such as ' Core ', ' Output ', ' Page ' ...) $frontendName = ' [...] ' ; Sets an array of options for the selected front end $frontendOptions = Array ([...]); Sets an array of options for the selected back-end $backendOptions = Array ([...]); Create an instance (of course, the last two parameters are optional) $cache = Zend_cache:: Factory ($frontendName, $backendName, $frontendOptions, $backendOptions) ;

(2) Marking record

Tags are a way to classify cache records. When you use the Save () method to save a cache, you can set one or more tokens for the cache record, and multiple tags are organized together in an array. After that you no longer need the cache record so that you can clear all the cached records for the specified tag.

$cache-> Save ($huge _data, ' Myuniqueid ', Array (' Taga ', ' TAGB ', ' TAGC '));

Note: The Zend_cache Save method can accept the fourth variable: $specificLifetime, if the variable is not false, a specific cache validity period will be set for the setting's cache.

(3) Cache cleanup

Deletes a cache record for a specific ID (label) using the Remove () method:

$cache-> Remove (' idtoremove ');

You can use the clean () method to delete multiple cache records in a single operation. For example, delete all cache records:

Clears all cache records $cache-> clean (zend_cache:: Cleaning_mode_all); Clears only expired $cache-> clean (zend_cache:: Cleaning_mode_old);

If you want to delete the cached items labeled ' Taga ' and ' TAGC ':

$cache-> Clean (zend_cache:: Cleaning_mode_matching_tag, Array (' Taga ', ' TAGC '));

Note: The available purge modes are: Cleaning_mode_all, Cleaning_mode_old, Cleaning_mode_matching_tag, and Cleaning_mode_not_matching_tag. Later, as its name implies, a tag array is combined in the purge operation to handle each of these elements.

--------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------

third, Zend_cache front-end

1.1.zend_cache_core

Introduction: Zend_cache_core is a special front end, because he is the core of the module. It is a generalized (generic) cache front-end and is extended by other classes. All front-end (Output,function,class. Inherits from Zend_cache_core so its methods and options (described below) should be available in other front-end, so there is no documentation. These options are passed to the factory method shown in the previous example.

Options Data Type Default Value Description
Caching Boolean True Turn caching on/off (useful for debugging cached scripts)
Cache_id_prefix String Null The prefix for all cache IDs, if set to NULL, no cache ID prefix is used. The cache ID prefix creates a namespace in the cache that allows multiple programs and the Internet to share the cache. Each program or Web site can use a different cache ID prefix, so a specific cache ID can be used multiple times.
Lifetime Int 3600 The cache lifetime (in seconds), and if set to NULL, the cache is always valid.
Logging Boolean False If set to True, log records (by using zend_log) are activated (but the system slows down)
Write_control Boolean True Open/Close Write control (the cache is read just after writing to detect corrupt entries), open write control slows down cache writes slightly but does not affect read (it can detect some Corr UpT cache files But it ' s not a perfect control)
Automatic_serialization Boolean False Turn on/off automatic serialization, which can be used to save non-string data directly (but very slowly)
Automatic_cleaning_factor Int 10 Turn off/Adjust the automatic cleanup process (garbage collector): 0 means that the cache is not automatically cleaned, 1 indicates that the cache is automatically cleaned, and if x > 1 is automatically cleaned 1 times after the x write operation.
Ignore_user_abort Boolean False If set to True, the core sets the Ignore_user_abort PHP flag in the Save () method to avoid cache crashes in some cases.
1.2. Examples
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

2.1 Zend_cache_frontend_output
Introduction: Zend_cache_frontend_output is an output capture front-end. It uses output buffers in PHP to capture all output between the start () and End () methods.

2.2 Examples

If it is a cache miss, the 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 ('

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.