PHP Cache Technology Detailed introduction and PHP cache implementation code

Source: Internet
Author: User
Tags apc
Some of the information is often constant, but still can change the information in the cache to speed up the display speed, which is very valuable, so-called cache, popular understanding is some saved on the server side of the common information. It is in the server with life and death, we can specify the time of the next update when saving the cache, For example, to update in 5 minutes

Data cache: In this case, the data cache refers to the database query PHP cache mechanism, each time you visit the page, will first detect the corresponding cache data exists, if not exist, connect to the database, get the data, and the query results are serialized and saved to the file, Later, the same query results are obtained directly from the cache table or file.

The most widely used example is the search function of discuz, which caches the result ID into a table and searches the cache table the next time the same keyword is searched.

For a common method, multi-table association, the schedule of the contents of the array is saved to a field in the main table, the need for the array decomposition, the advantage is only read a table, the disadvantage is that two data synchronization will be more than a few steps, the database is always the bottleneck, with the hard disk speed, is the key point.

Page cache:

Each time you visit the page, will detect the corresponding cache page file exists, if not exist, connect to the database, get data, display the page and generate the cache page file at the same time, so the next visit to the page file will play a role. (the template engine and some common PHP caching mechanism classes on the web usually have this feature)

Time-Triggered cache:

Check that the file exists and that the timestamp is less than the expiration time of the setting, and if the timestamp of the file modification is greater than the current timestamp minus the expiration timestamp, then cache is used, otherwise the cache is updated.

Content-Triggered caching:

Forces the PHP cache mechanism to be updated when data is inserted or updated.

Static cache:

Static caching refers to static, directly generated HTML or XML and other text files, there is an update when re-generated once, suitable for the less changing pages, this does not say.

The above content is a code-level solution, I direct CP other framework, too lazy to change, the content is almost, very easy to do, and will be used together in several ways, but the following content is the server-side caching scheme, non-code level, to have multi-party cooperation to do

Memory Cache:

Memcached is a high-performance, distributed memory object PHP caching mechanism system for reducing database load and increasing access speed in dynamic applications.

Buffer for PHP:

There are eaccelerator, APC, Phpa,xcache, this is not to say, search a bunch of a bunch of, see for yourself, know that this thing is OK

MySQL cache:

This is also non-code level, the classic database is used in this way, look at the following running time, 0.09xxx and the like
I stick paragraph according to the Blue Guy modify the latter part of the My.ini bar, 2G MyISAM table can be around 0.05S, it is said that he changed back and forth for a year

Reverse proxy-based Web caching:

such as Nginx,squid,mod_proxy (Apache2 and above are divided into mod_proxy and Mod_cache)
Examples of Nginx

Use Google to find some PHP caching technology methods

PHP cache implementation, the implementation of APC and file cache, inherited cache_abstract can be implemented to call third-party caching tools.

Refer to the Shindig cache class and APC.

<?php class Cacheexception extends Exception {}/** * <a href= "http://www.php.cn/category/79.html" > Cache </a > Abstract class */abstract class Cache_abstract {/** * read <a href= "http://www.php1.cn/category/79.html" > Cache &lt ;/a> variable * * @param string $key <a href= "http://www.php.cn/category/79.html" > Cache </a> Subscript * @re               Turn mixed */abstract public Function fetch ($KEY); /** * <a href= "http://www.php.cn/category/79.html" > Cache </a> Variables * * @param string $key <a HRE f= "http://www.php.cn/category/79.html" > Cache </a> Variable subscript * @param string $value <a href= "http://www.php.cn/cate               Gory/79.html "> Cache </a> Variable Value * @return BOOL */abstract Public function Store ($key, $value);  /** * Delete <a href= "http://www.php.cn/category/79.html" > Cache </a> Variables * * @param string $key    <a href= "http://www.php.cn/category/79.html" > Cache </a> Subscript   * @return Cache_abstract */Abstract Public Function Delete ($key);       /** * Clear (delete) except all <a href= "http://www.php.cn/category/79.html" > Cache </a> * * @return Cache_abstract               */Abstract Public Function clear (); /** * Lock <a href= "http://www.php.cn/category/79.html" > Cache </a> Variables * * @param string $key <a H ref= "http://www.php.cn/category/79.html" > Cache </a> Subscript * @return Cache_abstract */Abstract public fu           Nction Lock ($key); /** * <a href= "http://www.php.cn/category/79.html" > Cache </a> Variable Unlock * * @param string $key <a H ref= "http://www.php.cn/category/79.html" > Cache </a> Subscript * @return Cache_abstract */Abstract public fu           Nction unlock ($key); /** * Get <a href= "http://www.php.cn/category/79.html" > Cache </a> variable is locked * * @param string $key &L T;a href= "http://www.php.cn/category/79.html" > Cache</a> subscript * @return BOOL */abstract Public Function isLocked ($key); /** * Ensure that it is not locked state * up to $tries sleep waits to be unlocked, timeout skips and unlocks * * @param string $key <a href= "Http://www.php.cn/ca  Tegory/79.html "> Cache </a> Subscript */Public Function Checklock ($key) {if (! $this->islocked ($key))           {return $this;           } $tries = 10;           $count = 0;               Do {usleep (200);           $count + +;  } while ($count <= $tries && $this->islocked ($key));                       Do up to 10 sleep waits to unlock, timeout skips and unlocks $this->islocked ($key) && $this->unlock ($key);       return $this; }}/** * APC extension <a href= "http://www.php.cn/category/79.html" > Cache </a> Implementation * * * @category M    Jie * @package Cache * @author flowing Mengchun * @copyright Copyright (c) 2008-<cmpan (at) qq.com> * @license New BSD License * @versioN $Id: cache/apc.php version number 2010-04-18 23:02 Cmpan $ */class CACHE_APC extends Cache_abstract {protecte               D $_prefix = ' cache.mjie.net '; Public Function __construct () {if (!function_exists (' Apc_cache_info ')) {throw new cacheexception           (' APC extension didn ' t installed '); }}/** * save <a href= "http://www.php.cn/category/79.html" > Cache </a> Variables * @p           Aram String $key * @param mixed $value * @return BOOL */Public function Store ($key, $value) {       Return Apc_store ($this->_storagekey ($key), $value); }/** * Read <a href= "http://www.php.cn/category/79.html" > Cache </a> * * @param strin G $key * @return Mixed */Public function fetch ($key) {return Apc_fetch ($this->_storagekey (       $key));   }/** * Clear <a href= "http://www.php.cn/category/79.html" > Cache </a>    * * @return CACHE_APC */Public Function Clear () {Apc_clear_cache ();       return $this; }/** * Delete <a href= "http://www.php.cn/category/79.html" > Cache </a> Unit * * @return Ca           CHE_APC */Public Function Delete ($key) {apc_delete ($this->_storagekey ($key));       return $this; }/** * <a href= "http://www.php.cn/category/79.html" > Cache </a> Unit is locked * * @param String $key * @return BOOL */Public Function isLocked ($key) {if (Apc_fetch ($this->_storag EKey ($key).           '. Lock ')} = = = False) {return false;       } return true; }/** * Lock <a href= "http://www.php.cn/category/79.html" > Cache </a> Unit * * @param str ing $key * @return CACHE_APC */Public Function Lock ($key) {Apc_store ($this->_storagekey ($k EY). '.Lock ', ', 5);       return $this; }/** * <a href= "http://www.php.cn/category/79.html" > Cache </a> Cell Unlocked * * @param str ing $key * @return CACHE_APC */Public Function unlock ($key) {apc_delete ($this->_storagekey ($key).           '. Lock ');       return $this; }/** * Full <a href= "http://www.php.cn/category/79.html" > Cache </a> Name * * @param stri Ng $key * @return String */Private Function _storagekey ($key) {return $this->_prefix. '_' .       $key;  }}/** * file <a href= "http://www.php.cn/category/79.html" > Cache </a> Implementation * * * @category Mjie * @package Cache * @author pipelining Mengchun * @copyright Copyright (c) 2008-<cmpan (at) qq.com> * @license New BS        D License * @version $Id: cache/file.php version number 2010-04-18 16:46 Cmpan $ */class Cache_file extends Cache_abstract { Public $useSubdir = false;               Protected $_cachesdir = ' cache '; Public Function __construct () {if (Defined (' Data_dir ')) {$this->_setcachedir (data_dir.           '/cache '); }}/** * get <a href= "http://www.php.cn/category/79.html" > Cache </a> Files * * @p Aram String $key * @return String */protected function _getcachefile ($key) {$subdir = $this-& Gt;usesubdir? substr ($key, 0, 2).           '/' : ''; Return $this->_cachesdir. '/' . $subdir. $key.       '. php '; }/** * Read <a href= "http://www.php.cn/category/79.html" > Cache </a> Variable * To prevent information disclosure, <a href= "HT Tp://www.php.cn/category/79.html "> Cache </a> file format for PHP files, and to" <?php exit;? > "Start * * @param string $key <a href=" http://www.php.cn/category/79.html "> Cache </a> Subscript * @ret        Urn Mixed */public function fetch ($key) {$cacheFile = Self::_getcachefile ($key);   if (file_exists ($cacheFile) && is_readable ($cacheFile)) {//include mode//return in               Clude $cacheFile;           Serialized Way Return Unserialize (@file_get_contents ($cacheFile, False, NULL, 13));       } return false; }/** * <a href= "http://www.php.cn/category/79.html" > Cache </a> Variable * To prevent information disclosure, <a href= "http ://www.php.cn/category/79.html "> Cache </a> file format for PHP files, and to" <?php exit;? > "Start * * @param string $key <a href=" http://www.php.cn/category/79.html "> Cache </a> Variable subscript * @pa Ram string $value <a href= "http://www.php.cn/category/79.html" > Cache </a> Variable Value * @return BOOL */P           ublic function Store ($key, $value) {$cacheFile = Self::_getcachefile ($key);               $cacheDir = DirName ($cacheFile); if (!is_dir ($cacheDir)) {if (! @mkdir ($cacheDir, 0755, True)) {throw new CacheexceptioN ("Could not make cache directory"); }}//Use the Include method to//return the @file_put_contents ($cacheFile, ' <?php return '. Var_export ($value , true).               ';'); Return @file_put_contents ($cacheFile, ' <?php exit;? > '.       Serialize ($value)); }/** * Delete <a href= "http://www.php.cn/category/79.html" > Cache </a> Variables * * @param string $key <a href= "http://www.php.cn/category/79.html" > Cache </a> Subscript * @return Cache_file */Public fun ction Delete ($key) {if (Emptyempty ($key)) {throw new Cacheexception ("Missing argument 1 for Cache           _file::d elete () ");           } $cacheFile = Self::_getcachefile ($key);           if (! @unlink ($cacheFile)) {throw new Cacheexception ("Cache file could not being deleted");       } return $this; }/** * <a href= "http://www.php.cn/category/79.html" > Cache </a> Unit hasLock * * @param string $key * @return BOOL */Public Function isLocked ($key) {$cache           File = Self::_getcachefile ($key);           Clearstatcache (); Return File_exists ($cacheFile.       '. Lock '); }/** * Lock * * @param string $key * @return cache_file * * Public Function loc           K ($key) {$cacheFile = Self::_getcachefile ($key);           $cacheDir = DirName ($cacheFile);                       if (!is_dir ($cacheDir)) {if (! @mkdir ($cacheDir, 0755, True)) {if (!is_dir ($cacheDir)) {                   throw new Cacheexception ("Could not make cache directory"); }}}//Set <a href= "http://www.php.cn/category/79.html" > Cache </a> Lock file access and modification Room @touch ($cacheFile.           '. Lock ');       return $this; }/** * Unlock * * @param string $key * @return Cache_file */PublIC function Unlock ($key) {$cacheFile = Self::_getcachefile ($key); @unlink ($cacheFile.           '. Lock '); Return
  • 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.