Home Backend Development PHP Tutorial Detailed introduction to php caching technology and php caching implementation code_PHP tutorial

Detailed introduction to php caching technology and php caching implementation code_PHP tutorial

Jul 20, 2016 am 11:11 AM
php No introduce code by but information add accomplish technology cache able detailed still

Some information, such as information that is often constant but can still change, is placed in the cache to speed up the display. This is very valuable. The so-called cache is generally understood to be some shared information stored on the server. It is between the server and the server. Same as life and death, we can specify the next update time when saving the cache, for example, it should be updated every 5 minutes

Data cache: The data cache mentioned here refers to the database query PHP cache mechanism, each access When entering a page, it will first detect whether the corresponding cached data exists. If it does not exist, it will connect to the database, obtain the data, and serialize the query results and save them to the file. In the future, the same query results will be directly obtained from the cache table or file. get.

The most widely used example is the search function of Discuz, which caches the result ID into a table and searches the cache table first when searching for the same keyword next time.

As a common method, when multiple tables are associated, generate an array and save the contents in the attached table to a field in the main table. When necessary, decompose the array. The advantage of this is that only one table can be read. , the disadvantage is that there will be many more steps to synchronize the two data. The database is always the bottleneck. Trading the hard disk for speed is the key point of this.

Page cache:

Every time you access a page, it will first detect whether the corresponding cached page file exists. If it does not exist, connect to the database, get the data, display the page and generate a cache at the same time. Page file, so that the page file will come into play the next time you visit. (Template engines and some common PHP caching mechanism classes on the Internet usually have this function)

Time-triggered cache:

Check whether the file exists and the timestamp is less than the set expiration time. If the file is modified If the timestamp is greater than the current timestamp minus the expiration timestamp, use the cache, otherwise update the cache.

Content-triggered caching:

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

Static cache:

The static cache mentioned here refers to static, directly generating text files such as HTML or XML, and regenerating them when there are updates, which is suitable for pages that do not change much. , let’s not talk about it anymore.

The above content is a code-level solution. I directly CP other frameworks and am too lazy to change. The content is similar, it is easy to do, and can be used in several ways, but the following content is for the server End-end caching solutions, non-code level, require the cooperation of multiple parties to achieve

Memory caching:

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

PHP buffer:

There are eaccelerator, apc, phpa, xcache. I won’t talk about these. Search a bunch of them and see for yourself. If you know there is such a thing, OK

MYSQL cache:

This is also considered non-code level. Classic databases use this method. Look at the running time below, 0.09xxx and the like
I will post it According to the part of my.ini modified by the guy in blue, the 2G MYISAM table can be around 0.05S. It is said that he has modified it for almost a year

Web cache based on reverse proxy:

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

Send me a PHP caching implementation , implements apc and file caching, and inherits Cache_Abstract to call third-party caching tools.
Refer to shindig’s cache class and apc.

Php code

 代码如下 复制代码
class CacheException extends Exception {}  
/**
* Cache abstract class
*/  
abstract class Cache_Abstract {  
    /**
* Read cache variable
* *
* @param string $key cache subscript
* @return mixed
*/  
    abstract public function fetch($key);  
      
    /**
* Cache variable
* *
* @param string $key cache variable subscript
* @param string $value cache variable value
* @return bool
*/  
    abstract public function store($key, $value);  
      
    /**
* Delete cache variable *
* @param string $key cache index
* @return Cache_Abstract
*/  
    abstract public function delete($key);  
      
    /**
* Clear (delete) all caches
*
* @return Cache_Abstract
*/  
    abstract public function clear();  
      
    /**
* Lock cache variable *
* @param string $key cache index
* @return Cache_Abstract
*/  
    abstract public function lock($key);  
  
    /**
* Cache variable unlocking *
* @param string $key cache subscript*/  
    abstract public function unlock($key);  
  
    /**
* Get whether the cache variable is locked
* *
* @param string $key cache subscript
* @return bool
*/  
    abstract public function isLocked($key);  
  
    /**
* Make sure it is not locked
* Sleep at most $tries times to wait for unlocking, skip and unlock if timeout occurs
*
* @param string $key cache index
*/  
    public function checkLock($key) {  
        if (!$this->isLocked($key)) {  
            return $this;  
        }  
          
        $tries = 10;  
        $count = 0;  
        do {  
            usleep(200);  
            $count ++;  
        } while ($count <= $tries && $this->isLocked($key));  // 最多做十次睡眠等待解锁,超时则跳过并解锁  
  
        $this->isLocked($key) && $this->unlock($key);  
          
        return $this;  
    }  
}  
  
  
/**
* APC extended cache implementation
*
*
* @category Mjie
* @package Cache
* @author Liushui 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 variable
* * @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;  
    }  
      
    /** 
     * 锁定缓存单元 
     * 
     * @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 Liushui Mengchun
* @copyright Copyright (c) 2008- < ;cmpan(at)qq.com>
* @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 cached file
* *
* @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
* To prevent information leakage, the cache file format is a php file and starts with ""
*
* @param string $ key cache index
* @return mixed
*/  
    public function fetch($key) {  
        $cacheFile = self::_getCacheFile($key);  
        if (file_exists($cacheFile) && is_readable($cacheFile)) {  
            // include 方式  
            //return include $cacheFile;  
            // 系列化方式  
  
            return unserialize(@file_get_contents($cacheFile, false, NULL, 13));  
        }  
  
        return false;  
    }  
  
    /**
* Cache variable
* To prevent information leakage, the cache file format is a php file and starts with ""
*
* @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");  
            }  
        }  
    // 用include方式  
        //return @file_put_contents($cacheFile, '  
        return @file_put_contents($cacheFile, '' . serialize($value));  
    }  
  
    /**
* Delete cache variable *
* @param string $key cache subscript
* @return Cache_File
*/  
    public function delete($key) {  
        if(emptyempty($key)) {  
            throw new CacheException("Missing argument 1 for Cache_File::delete()");  
        }  
          
        $cacheFile = self::_getCacheFile($key);  
        if(!@unlink($cacheFile)) {  
            throw new CacheException("Cache file could not be deleted");  
        }  
  
        return $this;  
    }  
  
    /**
* Whether the cache unit has been locked
* *
* @param string $key
* @return bool
*/  
    public function isLocked($key) {  
        $cacheFile = self::_getCacheFile($key);  
        clearstatcache();  
        return file_exists($cacheFile . '.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");  
}                                                                                                             ;
}

/** 
     * 解锁 
     * 
     * @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

TechArticleSome information, such as information that often remains unchanged but can still change, is placed in the cache to speed up display. This It is very valuable. The so-called cache, the popular understanding is that some data are stored on the server side...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1653
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

See all articles