ThinkPHP3.1 quick start (10) cache

Source: Internet
Author: User
Tags delete cache
We must be good at using ThinkPHP's cache function. More importantly, we need to distinguish when the caching method is more effective. Caching is not omnipotent, and it is absolutely impossible to use it properly in projects. ThinkPHP provides convenient caching methods, including data caching, static caching, and query caching, supports dynamic data cache types including file methods, APC, Db, Memcache, Shmop, Sqlite, Redis, Eaccelerator, and Xcache, as well as customizable static cache rules, it also provides quick access methods.

Data Caching is performed in ThinkPHP. Generally, you do not need to directly operate the cache class. because the system has built-in encapsulation of cache operations, the data caching method recommended in version 3.1 is the cache method, the basic usage is:
( 3.1.2 The cache method has been incorporated into the S method. Therefore, it is not recommended to use the S method directly. it is consistent with the usage of the cache method described below.) 1 cache initialization
  1. Cache (array ('type' => 'xcache', 'expire '=> 60 ));
Parameters supported by the replication code cache initialization are different based on different cache methods. common parameters are as follows:
Expire Cache validity period (in seconds)
Prefix Cache ID prefix
Type Cache type
The core version only supports File caching. other caching methods support downloading a separate Cache Driver and placing it under the Extend/Driver/Cache/system directory, otherwise, an error message indicating that the cache type is not supported will appear.

Some caching methods have some special parameters, such as Memcache, and other parameters need to be configured:
  1. Cache (array ('type' => 'memcache', 'host' => '2017. 168.1.10 ', 'port' => '123', 'prefix' => 'think', 'expire' => 60 ));
For the global cache mode, we recommend that you add the prefix parameter to distinguish different applications to avoid confusion. 2 cache settings
  1. Cache ('A', $ value );
The copied code caches data according to the parameters during cache initialization. you can also change the parameters during cache settings, for example:
  1. Cache ('A', $ value, 300); // cache data for 300 seconds
Copy the code and even change the previous caching method or more parameters:
  1. Cache ('A', $ value, array ('type' => 'File', 'expire '=> 300); // cache data by file for 300 seconds
Copy the code. if you use the array method above to input parameters during cache settings, the subsequent cache access will be affected. 3 cache read
  1. $ Value = cache ('A ');
The copied code cache reads the value set in the previous cache, which will be affected by the parameters passed in during cache initialization or cache settings.
If the cache ID does not exist or has expired, false is returned; otherwise, the cache value is returned. 4. cache deletion
  1. Cache ('A', null );
Copy the code to delete the cached data marked as name.

To change the cache mode, you can initialize the cache again or use the following method:
  1. $ Cache = cache (array ('type' => 'xcache', 'prefix' => 'think', 'expire '=> 600 ));
  2. $ Cache-> name = 'value'; // sets the cache.
  3. $ Value = $ cache-> name; // Get the cache
  4. Unset ($ cache-> name); // deletes the cache.
If you have set a cache prefix for the copied code, the corresponding cache operation only identifies the cache prefix and does not affect other caches.
Data Caching supports cache queues. Simply put, you can limit the number of caches. you only need to specify the length parameter during initialization:
  1. Cache (array ('type' => 'xcache', 'length' => 100, 'expire '=> 60 ));
After the length parameter is set for the copied code, the system only caches the last 100 cached data records.

Quick cache if you only want to cache some simple data using files without the concept of validity period, the system also provides a quick cache method F for faster operations.
Data is saved in the DATA_PATH directory by default.
  1. F ('data', $ data );
Copy the code to cache Data and save it to the specified directory.
  1. F ('data', $ data, TEMP_PATH );
Copy code to obtain cache data
  1. $ Data = F ('data ');
Copy code to delete cache data
  1. F ('data', NULL );
The copy code F method supports automatic creation of cache sub-directories. data is cached under the DATA_PATH Directory. if the User sub-directory does not exist, it is automatically created:
  1. F ('user/data', $ data );
Copy code 3.1.2 to start the F method and use the wildcard batch delete function as follows:
  1. F ('user/* ', NULL );
Copy the code to delete the data cache under the DATA_PATH. 'user/'directory.
The system's built-in data field information cache uses the quick Cache mechanism.

The query cache function can be used to improve the performance of data queries with low timeliness requirements. you do not need to use the cache method to cache and obtain data.
The query cache function supports all databases and all cache methods and validity periods.
When using the query cache, you only need to call the cache method of the Model class, for example:
  1. $ Model-> cache (true)-> select ();
If the copied code uses the cache (true), the query cache is generated based on the current query SQL statement, by default, the cache mode is set by the DATA_CACHE_TYPE parameter (the default value is File, indicating File-based cache). the cache validity period is the time set by the DATA_CACHE_TIME parameter, you can also specify the cache query method and validity period separately:
  1. $ Model-> cache (true, 60, 'xcache')-> select ();
Copy the code to indicate that the current cache query method is xcache and the cache validity period is 60 seconds.
For the same query, if the cache method is not used, no Cache is obtained or generated, even if the cache method has been called before.
The query cache is only for internal calls. if you want to open the query cache to other programs, you can specify the query cache Key, for example:
  1. $ Model-> cache ('cache _ name', 60)-> select ();
By copying the code, you can obtain the cached content by using the S method externally,
  1. $ Value = S ('cache _ name ');
In addition to the select method, the query cache also supports the find and getField methods and their derivative methods (including statistical and dynamic query methods ). You can select the cache method and cache validity period as needed for specific applications.

To use the static cache function for static cache, you must enable the HTML_CACHE_ON parameter and use the HTML_CACHE_RULES parameter to set the static cache rule file.
Static rules are defined as follows:
  1. 'HTML _ CACHE_ON '=> true, // enable static cache
  2. 'HTML _ FILE_SUFFIX '=> '.shtml', // Set the static state to be suffixed with .shtml.
  3. 'HTML _ cache_rules' => array (
  4. 'Actionname (lower-case) '=> array ('static rule', 'static cache expires', 'additional rule '),
  5. 'Modulename (lower-case) '=> array ('static rule', 'static cache last', 'additional rule '),
  6. 'Modulename (lower-case): ActionName (lower-case) '=> array ('static rule', 'static cache validity period', 'additional rule '),
  7. '*' => Array ('static rules', 'static cache expires', and 'additional rules '),
  8. //... Static rules for more operations
  9. )
The root directory of the Copy code static cache file is under the path defined in HTML_PATH, and the static cache is only performed for operations that define static rules.
The first is to define global static rules for operations. for example, to define static rules for all read operations:
  1. 'Read' => array ('{id}', '60 ')
Copy the code. {id} indicates that $ _ GET ['id'] is the static cache file name, and the second parameter indicates that the cache is 60 seconds.
The second is to define global static module rules. for example, to define static rules for all User modules:
  1. 'User: '=> array ('user/{: action }_{ id}', '123 ')
Copy the code. {: action} indicates the name of the current operation.
The third is to define the static rules for operations of a module. for example, we need to define the read operations of the Blog module for static caching.
  1. 'Blog: read' => array ('{id}', 0)
The replication code has some special rules, such as the definition of static rules for empty modules and empty operations. you can use the following method:
  1. 'Empty: index' => array ('{: module }_{: action}', 0) // defines static rules for empty modules.
  2. 'User: _ empty' => array ('user/{: action} ', 0) // defines static rules for null operations
The fourth way to copy code is to define global static cache rules, which are used in special circumstances and can be applied to any module operations, such
  1. '*' => Array ('{$ _ SERVER. REQUEST_URI | md5 }'),
Copy the code and cache it based on the current URL.

Static rules are used to define the name of the static file to be generated. do not conflict with the definition of static rules. The statement can be as follows:
1. Use system variables including _ GET _ REQUEST _ SERVER _ SESSION _ COOKIE
Format:
{$ _ ××× | Function}

For example:
  1. {$ _ GET. name}
  2. {$ _ SERVER. REQUEST_URI | md5}
Copy code 2. use framework-specific variables
For example, {: app}, {: group}, {: module}, and {: action} indicate the current project name, group name, module name, and Operation Name respectively.

3. use the _ GET variable
{Var | function} that is, {id} is equivalent to {$ _ GET. id}

4. directly use functions
{| Function} example:
  1. {| Time}
Copy code 5. support mixed definition. for example, we can define a static rule as follows:
  1. '{Id}, {name | md5 }'
Copy characters other than {} as strings. if "/" is included, a directory is automatically created.
For example, define the following static rules:
  1. {: Module}/{: action }_{ id}
The copy code creates a copy name subdirectory under the static directory, and then writes the operation name _id.shtml file.
The unit of static validity is seconds. If this parameter is not specified, the setting value of the configuration parameter HTML_CACHE_TIME is obtained. If this parameter is set to 0, the cache is permanently cached.
Additional rules are usually used to perform function operations on static rules, such
  1. 'Read' => array ('think {id}, {name} ', '60', 'md5 ')
The static rules translated by the copied code are md5 ('think'. $ _ GET ['id']. ','. $ _ GET ['name']).
Configuration parameters related to static cache include:
  1. HTML_CACHE_ON: whether static cache is enabled
  2. HTML_FILE_SUFFIX: The default value for static file suffix configuration is. html.
  3. HTML_CACHE_TIME: default static cache validity period: 60 seconds by default, which can be overwritten by the definition of static rules.
Copy code
To sum up, we should be good at using ThinkPHP's cache function. More importantly, we should distinguish when to use which cache method is more effective. The cache is not omnipotent, and it is absolutely impossible without a cache.

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.