Simple use of Zend_Cache

Source: Internet
Author: User
Tags crc32
Caching in ZendFramework is performed by the front-end, and through the backend adapter (File, Sqlite, Memcache ...) And a flexible IDs and Tags system (identifier and tag system) to store cache records. module (Zend_Cache_Core)

1. fast Zend_Cache browsing

Zend_Cache provides a general method for caching any data.

Caching in Zend Framework is performed by the front-end, and through the backend adapter (File, Sqlite, Memcache ...) And a flexible IDs and Tags system (identifier and tag system) to store cache records. the core of the Zend_Cache_Core module is universal, flexible, and configurable. for specific needs, for convenience, there are some front-ends inherited from Zend_Cache_Core: Output, File, Function, and Class.

(1) Call Zend_Cache: factory () to obtain a front-end

$ FrontendOptions = array (
'Lifetime' => 7200, // two-hour cache life cycle
'IC IC _ serialization' => true
);
$ BackendOptions = array (
'Cache _ dir' => './tmp/' // Directory for storing cached files
);
// Obtain a Zend_Cache_Core object
$ Cache = Zend_Cache: factory ('core', 'file', $ frontendOptions, $ backendOptions );

(2) cache the query results from the database.

Now we have a front-end that can cache any type of data (serialization is enabled '). for example, you can cache a result from an expensive database query. after the result is cached, you no longer need to connect to the database; data is directly retrieved and deserialized in the cache.

// $ Cache has been initialized in the previous example
// Check whether a cache exists:
If (! $ Result = $ cache-> load ('myresult ')){
// Cache miss; connection to database
$ Db = Zend_Db: factory ([...]);
$ Result = $ db-> fetchAll ('select * FROM huge_table ');
$ Cache-> save ($ result, 'myresult'); // use the zend_cache object to cache the query results.
} Else {
// Read the $ result content cached in the myresult label in the cache name.
Echo "This one is from cache! Nn ";
}
Print_r ($ result );

(3) use Zend_Cache to output the front-end cache output
By adding the conditional logic, we 'Mark up' (mark) the segments (sections) that you want to cache the output, in start () and end () these sections are encapsulated between methods (this is similar to the first example and is the core cache policy ). internally, output your data as usual. when you execute the end () method, all previous outputs are cached. during the next running, the entire segment (the code before the end () method call) will be skipped and the execution will be skipped and the data will be retrieved directly from the Cache (as long as the Cache record is valid ).

// Set the cache storage time and whether to serialize the object.
$ FrontendOptions = array (
'Lifetime' => 30, // cache lifeTime of 30 seconds
'IC IC _ serialization' => false // this is the default anyway s
);
// Configure the cache storage path for the backend adapter
$ BackendOptions = array ('cache _ dir' => './tmp /');
$ Cache = Zend_Cache: factory ('output', 'file', $ frontendOptions, $ backendOptions );
// Pass 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 is never cached ('. time ().').';

Summary: when Zend_Cache is used, it is important to note the Cache identifier (the parameters passed to save () and start ). it must be unique for each resource you Cache. otherwise, unrelated cache records will overwrite each other. Worse, it will lead to incorrect display results. II. cache principles

Cache principle:

Zend_Cache has three key concepts.

The first is the unique identifier (a string) used to identify the cache record ).

The second is the 'lifetime' command. as you can see in the example, it defines the lifeTime of the cache record (beyond this value, the cache record is destroyed ).

The third key concept is conditional execution. some of your code can be skipped to accelerate performance. front-end functions (such. zend_Cache_Core: get () returns false if the cache does not hit, which enables the user to process if (){... } The condition in the statement contains the part of the code that they want to cache (or skip), and whether to save the blocks you have generated (for example, Zend_Cache_Core: save ()).

Note: 'cache hit 'is a term that indicates that when a cache record is available, it is valid and 'refresh' (in other words, it is not expired yet ). 'cache miss 'indicates that Cache miss occurs when the required data cannot be found in the Cache. when a Cache miss occurs, you must generate your data and make it cached. for Cache hits, the backend automatically and transparently retrieves Cache records from the Cache.

You must use Zend_Cache: factory () to obtain the front-end instance. the front-end or backend instance you instantiate cannot work as expected.

(1) Zend_Cache factory method

// We choose a backend (for example 'file' or 'sqlite '...)
$ BackendName = '[...]';
// Select a front end (for example, 'core', 'output', 'page '...)
$ FrontendName = '[...]';
// Set an array of options for the selected front-end
$ FrontendOptions = array ([...]);
// Set an array of options for the selected backend
$ BackendOptions = array ([...]);
// Create an instance (of course, the last two parameters are optional)
$ Cache = Zend_Cache: factory ($ frontendName, $ backendName, $ frontendOptions, $ backendOptions );

(2) mark a record

Marking is a way to classify cache records. when you use the save () method to save a cache, you can set one or more tags for the cache record, multiple tags are organized in an array. after that, you no longer need this cache record. you can clear all the cache records of 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 this variable is not set to false, a specific cache validity period will be set for the set cache.

(3) cache cleaning

Delete the Cache record of a specific id (tag) by using the remove () method:

$ Cache-> remove ('idtoremove ');

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

// Clear all cache records
$ Cache-> clean (Zend_Cache: CLEANING_MODE_ALL );
// Only clear expired
$ Cache-> clean (Zend_Cache: CLEANING_MODE_OLD );

If you want to delete the cache items marked as 'taga' and 'tagc:

$ Cache-> clean (Zend_Cache: CLEANING_MODE_MATCHING_TAG, array ('taga ', 'tagc '));

Note: available CLEANING_MODE_ALL, CLEANING_MODE_OLD, CLEANING_MODE_MATCHING_TAG, and CLEANING_MODE_NOT_MATCHING_TAG. as its name implies, a tag array is combined in the clear operation to process each element.

III. Zend_Cache frontend

1.1.Zend _ Cache_Core

Introduction: Zend_Cache_Core is a special front-end because it is the core of the module. it is a general (generic) cache front end, and is extended by other classes. all front ends (output, function, class ..) inherited from Zend_Cache_Core. Therefore, its methods and options (described below) should be available in other front-ends, so no documentation is made here. these options are passed to the factory method shown in the preceding example.

Caching Boolean True Enable/disable caching (useful for debugging cached scripts)
Cache_id_prefix String Null The prefix of all cache IDs. if it is set to null, no cache id prefix is used. The cache id prefix creates a namespace in the cache, allowing multiple programs to share the cache with the Internet. Each program or website can use different cache id prefixes, so a specific cache id can be used multiple times.
Lifetime Int 3600 The cache duration (in seconds). if it is set to null, the cache will always be valid.
Logging Boolean False If it is set to true, log records (by using Zend_Log) are activated (but the system will slow down)
Write_control Boolean True Enable/disable write control (the cache is read just after writing to detect into UPT entries ), enabling write control slightly slows down the cache write speed but does not affect reading (it can detect some cached UPT cache files but it's not a perfect control)
Automatic_serialization Boolean False Enable/disable automatic serialization, which can be used directly to save non-string data (but very slow)
Automatic_cleaning_factor Int 10 Disable/adjust the automatic cleaning process (garbage collector): 0 indicates that the cache is not cleared automatically, 1 indicates that the cache is cleared automatically, and if x> 1 indicates that the cache is automatically cleared once after x write operations.
Ignore_user_abort Boolean False If it is set to true, the core will set ignore_user_abort PHP flag in the save () method to avoid cache crash in some cases.
1. 2. example // 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 the output buffer in PHP to capture all outputs between the start () and end () methods.

2.2 Example

// 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 ().').';

Zend_Cache_Frontend_File, Zend_Cache_Frontend_Function, and Zend_Cache_Front_Page

IV. Zend_Cache backend

1.1. Zend_Cache_Backend_File: After that, the cache records are stored in files (in a selected directory ).

1.2 File backend options:

Cache_dir String '/Tmp /' Directory for storing cached files
File_locking Boolean True Enable/disable file locking: In the case of poor conditions, cache interruption can be avoided, but it does not help in multi-threaded Web servers or NFS file systems.
Read_control Boolean True Enable/disable read control: If enabled, the control key is embedded in the cache file and compared with the value calculated after reading.
Read_control_type String 'Crc32 ′ Read control type (only when read control is enabled ). available values: 'md5' (best but slowest), 'crc32' (slightly less secure, but faster, better choice), 'adler32' (new choice, faster than crc32 ), 'strlen' for a length only test (fastest ).
Hashed_directory_level Int 0 Hash directory structure level: 0 indicates "directory structure without hash", 1 indicates "level 1 directory structure", 2 indicates "level 2 directory "... The second option is to accelerate the cache when you have thousands of cached files. only the benchmark test can help you select the appropriate value. maybe 1 or 2 is a good start.
Hashed_directory_umask Int 0700 Unix mask of directory structure
File_name_prefix String 'Zend _ cache' Cache file prefix; be careful with this option, because when clearing the cache, a value that is too generic in the system cache Directory (like/tmp) will cause a disaster.
Cache_file_umask Int 0700 Cached file mask
Metatadatas_array_max_size Int 100 Maximum internal size of the metadatas array (unless you know what you are doing, do not change this value)

2.1. Zend_Cache_Backend_Sqlite: After that, the cache records are stored in the SQLite database.

2.2. Sqlite backend options

Cache_db_complete_path (mandatory) String Null SQLite database integrity and path (including file name)
Automatic_vacuum_factor Int 10 Disable/adjust the automatic cleaning process. during the automatic cleaning process, and make it smaller are performed on database files. when clean () or delete () is called, 0 indicates that the database files are not cleared automatically; 1 indicates automatic cleaning (when the delete () or clean () method is called); x (integer)> 1 => when the delete () or clean () method is called () methods are randomly cleared once or twice.

3.1. Zend_Cache_Backend_Memcached: This backend stores cache records on the memcached server. memcached is a high-performance, distributed memory object cache system. to use this end, you need a memecached daemon and memcache PECL extension.

3.2. Memcached backend options

Servers Array Array ('host' => 'localhost', 'port' => 11211, 'persistent' => true )) An array of memcached servers. each memcached server is described as an associated array: 'host' => (string): name of the memcached server, 'port' => (int ): memcached server port, 'persistent' => (bool): whether to use a persistent connection to the memcached server
Compression Boolean False If you want to use data compression, set it to true

Ps: For the time being, zend_cache records so many records first. basically, zend_cache is easy to use and has an ideal effect!

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.