Home Backend Development PHP Tutorial Detailed explanation of the application of caching technology in PHP_PHP Tutorial

Detailed explanation of the application of caching technology in PHP_PHP Tutorial

Jul 13, 2016 pm 05:29 PM
php web application powerful technology of cache Script explain design detailed language

PHP,一门最近几年兴起的web设计脚本语言,由于它的强大和可伸缩性,近几年来得到长足的发展,php相比传统的asp网站,在速度上有绝对的优势,想mssql转6万条数据php如需要40秒,asp不下2分钟.但是,由于网站的数据越来越多,我们渴求能更快速的调用数据,不必要每次都从数据库掉,我们可以从其他的地方,比方一个文件,或者某个内存地址,这就是php的缓存技术,也就是Cache技术.


一般来说,缓存的目的是把数据放在一个地方让访问的更快点,毫无疑问,内存是最快的,但是,几百M的数据能往内存放么?这不现实,当然,有的时候临时放如服务器缓存,如ob_start()这个缓存页面开启的话在发送文件头之前页面内容都被缓存在内存中,知道等页面输出自动清楚或者等待ob_get_contents的返回,[或者被ob_end_clean显示的清除,这在静态页面的生成中能很好的利用,在模板中能得到很好的体现,我的这篇文章深入的讨论了:

 谈PHP生成静态页面,这是一种方式,但这是临时性的,不是解决我们问题的好方法.

另外,在asp中有一对象application,可以保存公用的参数,这也算点缓存,但在php,我至今没看到开发者产出这种对象,的确,没必要.asp.net的页面缓存技术就用的是viewstate,而cache就是文件关联,(不一定准确),文件被修改,更新缓存,文件没被修改而且不超时(注释1),就读取缓存,返回结果,就是这个思路,看看这个源码:

class cache{
/*
Class Name: cache
Description: control to cache data,$cache_out_time is a array to save cache date time out.
Version: 1.0
Author: Old farmer cjjer
Last modification:2006-2-26
Author URL: http://www.cjjer.com
*/
private $cache_dir;
private $expireTime=180;//The cache time is 60 seconds
function __construct($cache_dirname){
if(!@is_dir($cache_dirname)){
if(!@mkdir($cache_dirname ,0777)){
                                                                                                                                                                                    ,,,,,,,,,,,;,; ;cache_dir = $cache_dirname;
}
function __destruct(){
echo Cache class bye.;
}

function get_url() {
if (!isset( $_SERVER[REQUEST_URI])) {
                                                                                                               🎜>                                                                                                            _SERVER[QUERY_STRING])) ? ? . $_SERVER[QUERY_STRING] : ;
}

return $url;
}

function warn($errorstring){
echo "An error occurred:
".$errorstring."
";
}

function cache_page($pageurl,$pagedata){
if(!$fso=fopen($pageurl,w)){
$this->warns(Cache file cannot be opened.);// trigger_error
return false;
}
if(!flock($fso,LOCK_EX)){//LOCK_NB, exclusive lock
$this->warns(Cache file cannot be locked.) ;//trigger_error
return false;
}
if(!fwrite($fso,$pagedata)){//Write byte stream, serialize to write other formats
$this-> ;warns(Unable to write to cache file.);//trigger_error
return false;
}
flock($fso,LOCK_UN);//Release lock
fclose($fso);
return true;
}

function display_cache($cacheFile){
if(!file_exists($cacheFile)){
$this->warn(Cache file cannot be read. );//trigger_error
return false;
}
echo Read cache file:.$cacheFile;
//return unserialize(file_get_contents($cacheFile));
$fso = fopen ($cacheFile, r);
$data = fread($fso, filesize($cacheFile));
fclose($fso);
return $data;
}

function readData($cacheFile=default_cache.txt){
$cacheFile = $this->cache_dir."/".$cacheFile;
if(file_exists($cacheFile)&&filemtime($cacheFile)>( time()-$this->expireTime)){
                                                                                     else{
                $data="from here wo can get it from mysql database,update time is ".date(l dS of F Y h:i:s A).", The expiration time is: ".date(l dS of F Y h:i:s A,time()+$this->expireTime)."----------";
$this ->cache_page($cacheFile,$data);
}
      return $data;
}



}
?>

Below I will interrupt this code to explain it line by line.
Three: Program Dialysis

This cache class (class is nothing good) Scared. Please continue reading) The name is cache and has 2 attributes:

private $cache_dir;
private $expireTime=180;

$cache_dir is the parent directory of the relative website directory where the cache file is placed, $expireTime(Comment One ) is the expiration time of our cached data, mainly based on this idea:
When the data or file is loaded, first determine whether the cache file exists, return false, and the file was last modified Is the sum of time and cache time greater than the current time? If it is greater, it means that the cache has not expired. If it is smaller, it returns false. When false is returned, the original data is read, written to the cache file, and the data is returned. ,

Then look at the program:

function __construct($cache_dirname){
if(!@is_dir($cache_dirname)){
if(!@mkdir($cache_dirname,0777)){
$this-> ;warn(The cache file does not exist and cannot be created, it needs to be created manually.); >
When the class is instantiated for the first time, a default function is constructed with parameters to cache the file name. If the file does not exist, create a folder with editing permissions. An exception will be thrown when the creation fails. Then $ of the cache class The cache_dir attribute is set to this folder name. All our cache files are in



http://www.bkjia.com/PHPjc/509203.html

www.bkjia.com

true

TechArticlePHP, a web design scripting language that has emerged in recent years, due to its power and scalability, has recently PHP has made great progress in the past few years. Compared with traditional ASP websites, PHP has an absolute advantage in speed. I think...
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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

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,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

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.

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.

See all articles