Table of Contents
您可能感兴趣的文章
Home php教程 php手册 PHP缓存操作实例详解

PHP缓存操作实例详解

Jun 13, 2016 am 09:36 AM
php Example operate cache Detailed explanation

为什么要使用缓存技术?理由很简单:提高效率。在程序开发中,获取信息的方式主要是查询数据库,除此以外,也可能是通过Web Services或者别的某种方法,无论哪种方法,在大量的并发访问面前,它们都可能成为效率的瓶颈,为了解决这些问题,人们提出了很多解决方案,其中一些是利用优化软件(如:APC,Eaccelerator,Zend Optimizer等等)来提高程序的运行效率,合理的运用这些软件,往往能使程序的运行效率得到数量级上的提升,但前提是你必须拥主机的控制权,以便能够安装这些软件,如果你使用的是虚拟主机的话,那么只能祈祷你的服务提供商已经预装了某个优化软件,否则就必须自己使用PHP来实现相应的缓存功能。如果这让你感到无所适从,相信下面的这段缓存操作类的代码能给你一些有用的启发。(PHP缓存操作实例详解)

<?php
/**
+----------------------------------------------------------  
* franklin 缓存操作类  
+----------------------------------------------------------  
* 文件名称  cache.php  
+----------------------------------------------------------  
* 文件描述  缓存操作类  
+----------------------------------------------------------  
* 作 者  http://www.phpernote.com  
+----------------------------------------------------------  
* 时 间  2012-05-05  
+----------------------------------------------------------  
*/  

class cache{
//查询参数
protected $options=array();
//缓存次数
protected $cacheCount=0;
//缓存时间
protected $cachetime=60;
//缓存路径
protected $cachePath='cache/';
//数据返回类型, 1代表数组, 2代表对象
protected $returnType=1;
/**  
* 读取缓存  
* @param string $id  缓存名称  
* @param int $time 缓存有效时间,默认为60秒,0为永远失效  
* @param string $path缓存文件存放路径  
* @accesspublic readCache  
* @returnmixed如果读取成功返回缓存内容, 否则返回NULL  
*/  
public function readCache($id,$time,$Path=''){
	$id=md5($id);
	$this->cachePath=emptyempty($Path)?$this->cachePath:$Path;
	$this->cachetime=emptyempty($time)?$this->cachetime:$time;
	$file=$this->cachePath.$id.'.php';
	if(file_exists($file)){
		//缓存过期
		if((filemtime($file)+$time)<time()){
			@unlink($file);
			return NULL;
		}
		if(1===$this->returnType){
			$row=include $file;
		}else{
			$data=file_get_contents($file);
			$row=unserialize($data);
		}
		return $row;
	}
	return NULL;
}
/**  
* 写入缓存  
*  
* @accesspublic  
* @param mixed$data缓存内容  
* @returnbool是否写入成功  
*/  

public function writeCache($id,$data,$Path=''){ 
	$this->cacheCount++;
	$id=md5($id);
	$this->cachePath=emptyempty($Path)?$this->cachePath:$Path;
	$file=$this->cachePath.$id.'.php';
	chmod($this->cachePath,777);
	if(1===$this->returnType){
		$data='<?php return '.var_export($data, TRUE).'; ?>';
	}else{
		$data=serialize($data);
	}
	return file_put_contents($file, $data);
}
/**  
* 删除指定缓存  
*  
* @accesspublic  
* @param mixed$id缓存名称  
* @returnbool是否删除成功  
*/  
public function delCache($id,$Path=''){  
	$id=md5($id);
	$this->cachePath=emptyempty($Path)?$this->cachePath:$Path;
	$file=$this->cachePath.$id.'.php';
	if(file_exists($file)){
		return unlink($file);
	}
	return NULL;
}
/**  
* 删除所有缓存  
*  
* @accesspublic  
* @param mixed$dir缓存名称  
* @returnbool清除所有缓存是否成功  
*/  
public function delAllCache($Path=''){  
	$id=md5($id);
	$this->cachePath=emptyempty($Path)?$this->cachePath:$Path;
	$path=$this->cachePath;
	if(is_dir($path)){
		if($dh=opendir($path)){
			while(($file=readdir($dh))!==false){
				if($file!='..'&$file!='.'){
					if(is_dir($path.'/'.$file)){
						if(!delDir($path.'/'.$file)){
							return 0;
						}
					}else{
						if(!unlink($path.'/'.$file)){
							return 0;
						}
					}
				}
			}
			closedir($dh);
		}
		return 1;
	}
}
}
Copy after login

以上缓存操作类的引用方法如下:

<?php
include('cache.php');
$data=array('http://www.phpernote.com','http://www.baidu.com','http://www.google.cn');
$cache=new cache();
$id='test';
//写入缓存
$cache->writeCache($id,$data);
//读缓存并打印
$name_row=$cache->readCache($id,120);
print_r($name_row);
//删除某个变量
$cache->delCache($id);
//删除全部缓存
$cache->delAllCache();
Copy after login

注意要保证cache目录(即缓存目录)存在并且可写。

您可能感兴趣的文章

  • php获取当前操作系统类型
  • 用PHP函数memory_get_usage获取当前PHP内存消耗量以实现程序的性能优化
  • PHP生成迅雷、快车、QQ旋风下载链接的实例
  • php如何判断当前的操作系统是linux还是windows
  • php用ZipArchive函数实现文件的压缩与解压缩
  • php实现多重继承实例
  • PHP缓存技术详解
  • php获取目录所有文件并将结果保存到数组的程序
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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

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

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

CakePHP Quick Guide CakePHP Quick Guide Sep 10, 2024 pm 05:27 PM

CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks.

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 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,

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

See all articles