PHP Cache Technology Detailed introduction and PHP cache implementation Code _php tutorial

Source: Internet
Author: User
Tags apc delete cache
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 code

The code is as follows Copy Code
Class Cacheexception extends Exception {}
/**
* Caching Abstract classes
*/
Abstract class Cache_abstract {
/**
* Read Cache variables
*
* @param string $key cache subscript
* @return Mixed
*/
Abstract public Function fetch ($KEY);

/**
* Cache Variables
*
* @param string $key cache variable Subscript
* @param string $value The value of the cache variable
* @return BOOL
*/
Abstract Public function Store ($key, $value);

/**
* Delete Cache variables
*
* @param string $key cache subscript
* @return Cache_abstract
*/
Abstract Public Function Delete ($key);

/**
* Clear (delete) except all caches
*
* @return Cache_abstract
*/
Abstract public Function clear ();

/**
* Lock Cache variables
*
* @param string $key cache subscript
* @return Cache_abstract
*/
Abstract Public Function lock ($key);

/**
* Cache Variable Unlocked
*
* @param string $key cache subscript
* @return Cache_abstract
*/
Abstract public Function unlock ($key);

/**
* Gets whether the cache variable is locked
*
* @param string $key cache subscript
* @return BOOL
*/
Abstract public Function isLocked ($key);

/**
* Make sure not locked status
* Up to $tries sleep waiting to be unlocked, timeout skipped and unlocked
*
* @param string $key cache 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 to skip and unlock

$this->islocked ($key) && $this->unlock ($key);

return $this;
}
}


/**
* APC Extended Cache implementation
*
*
* @category Mjie
* @package Cache
* @author Water Mengchun
* @copyright Copyright (c) 2008-
* @license New BSD License
* @version $Id: cache/apc.php version number 2010-04-18 23:02 Cmpan $
*/
Class Cache_apc extends Cache_abstract {

protected $_prefix = ' cache.mjie.net ';

Public Function __construct () {
if (!function_exists (' Apc_cache_info ')) {
throw new Cacheexception (' APC extension didn ' t installed ');
}
}

/**
* Save Cache variables
*
* @param string $key
* @param mixed $value
* @return BOOL
*/
Public function Store ($key, $value) {
Return Apc_store ($this->_storagekey ($key), $value);
}

/**
* Read Cache
*
* @param string $key
* @return Mixed
*/
Public function Fetch ($key) {
Return Apc_fetch ($this->_storagekey ($key));
}

/**
* Clear Cache
*
* @return CACHE_APC
*/
Public Function Clear () {
Apc_clear_cache ();
return $this;
}

/**
* Delete Cache unit
*
* @return CACHE_APC
*/
Public Function Delete ($key) {
Apc_delete ($this->_storagekey ($key));
return $this;
}

/**
* Whether the cache unit is locked
*
* @param string $key
* @return BOOL
*/
Public Function isLocked ($key) {
if (Apc_fetch ($this->_storagekey ($key). '. Lock ')) = = = = False) {
return false;
}

return true;
}

/**
* Lock Cache Unit
*
* @param string $key
* @return CACHE_APC
*/
Public function Lock ($key) {
Apc_store ($this->_storagekey ($key). '. Lock ', ', 5 ';
return $this;
}

/**
* Cache Unit Unlocked
*
* @param string $key
* @return CACHE_APC
*/
Public function Unlock ($key) {
Apc_delete ($this->_storagekey ($key). '. Lock ');
return $this;
}

/**
* Full Cache Name
*
* @param string $key
* @return String
*/
Private Function _storagekey ($key) {
Return $this->_prefix. '_' . $key;
}
}

/**
* File Cache implementation
*
*
* @category Mjie
* @package Cache
* @author Water Mengchun
* @copyright Copyright (c) 2008-
* @license New BSD 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 cache files
*
* @param string $key
* @return String
*/
protected function _getcachefile ($key) {
$subdir = $this->usesubdir? substr ($key, 0, 2). '/' : '';
Return $this->_cachesdir. '/' . $subdir. $key. '. php ';
}

/**
* Read Cache variables
* In order to prevent information disclosure, the cache file format is php file and " "Start
*
* @param string $key cache subscript
* @return Mixed
*/
Public function Fetch ($key) {
$cacheFile = Self::_getcachefile ($key);
if (file_exists ($cacheFile) && is_readable ($cacheFile)) {
Include method
return include $cacheFile;
Serialization method

Return Unserialize (@file_get_contents ($cacheFile, False, NULL, 13));
}

return false;
}

/**
* Cache Variables
* In order to prevent information disclosure, the cache file format is php file and " "Start
*
* @param string $key cache variable Subscript
* @param string $value The value of the cache variable
* @return BOOL
*/
Public 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
Return @file_put_contents ($cacheFile, '
Return @file_put_contents ($cacheFile, ' ' . Serialize ($value));
}

/**
* Delete Cache variables
*
* @param string $key cache subscript
* @return Cache_file
*/
Public Function 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;
}

/**
* Whether the cache unit is locked
*
* @param string $key
* @return BOOL
*/
Public Function isLocked ($key) {
$cacheFile = Self::_getcachefile ($key);
Clearstatcache ();
Return File_exists ($cacheFile. '. Lock ');
}

/**
* Lock
*
* @param string $key
* @return Cache_file
*/
Public function Lock ($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");
}
}
}

Setting access and modification times for cache lock files
@touch ($cacheFile. '. Lock ');
return $this;
}

/**
* Unlock
*
* @param string $key
* @return Cache_file
*/
Public function Unlock ($key) {
$cacheFile = Self::_getcachefile ($key);
@unlink ($cacheFile. '. Lock ');
Return

http://www.bkjia.com/PHPjc/444684.html www.bkjia.com true http://www.bkjia.com/PHPjc/444684.html techarticle 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 ...

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