How to implement PHP cache class

小云云
Release: 2023-03-20 11:58:01
Original
1224 people have browsed it

本文主要和大家分享一个PHP缓存类实现的实例,希望能帮助到大家。

<?php
/*
* 缓存类 cache
*/
class cache {
//缓存目录
var $cacheRoot = "./cache/";
//缓存更新时间秒数,0为不缓存
var $cacheLimitTime = 0;
//缓存文件名
var $cacheFileName = "";
//缓存扩展名
var $cacheFileExt = "php";
/*
  * 构造函数
  * int $cacheLimitTime 缓存更新时间
  */
function cache( $cacheLimitTime ) {
  if( intval( $cacheLimitTime ) )
  $this->cacheLimitTime = $cacheLimitTime;
  $this->cacheFileName = $this->getCacheFileName();
  ob_start();
} 
/*
  * 检查缓存文件是否在设置更新时间之内
  * 返回:如果在更新时间之内则返回文件内容,反之则返回失败
  */
function cacheCheck(){
  if( file_exists( $this->cacheFileName ) ) {
  $cTime = $this->getFileCreateTime( $this->cacheFileName );
  if( $cTime + $this->cacheLimitTime > time() ) {
  echo file_get_contents( $this->cacheFileName );
  ob_end_flush();
  exit;
  }
  }
  return false;
}
/*
  * 缓存文件或者输出静态
  * string $staticFileName 静态文件名(含相对路径)
  */
function caching( $staticFileName = "" ){
  if( $this->cacheFileName ) {
  $cacheContent = ob_get_contents();
  ob_end_flush();
  if( $staticFileName ) {
  $this->saveFile( $staticFileName, $cacheContent );
  }
  if( $this->cacheLimitTime )
  $this->saveFile( $this->cacheFileName, $cacheContent );
  }
} 
/*
  * 清除缓存文件
  * string $fileName 指定文件名(含函数)或者all(全部)
  * 返回:清除成功返回true,反之返回false
  */
function clearCache( $fileName = "all" ) {
  if( $fileName != "all" ) {
  $fileName = $this->cacheRoot . strtoupper(md5($fileName)).".".$this->cacheFileExt;
  if( file_exists( $fileName ) ) {
  return @unlink( $fileName );
  }else return false;
  }
  if ( is_dir( $this->cacheRoot ) ) {
  if ( $dir = @opendir( $this->cacheRoot ) ) {
  while ( $file = @readdir( $dir ) ) {
  $check = is_dir( $file );
  if ( !$check )
  @unlink( $this->cacheRoot . $file );
  }
  @closedir( $dir );
  return true;
  }else{
  return false;
  }
  }else{
  return false;
  }
}
/*根据当前动态文件生成缓存文件名*/
function getCacheFileName() {
  return $this->cacheRoot . strtoupper(md5($_SERVER["REQUEST_URI"])).".".$this->cacheFileExt;
}
/*
  * 缓存文件建立时间
  * string $fileName 缓存文件名(含相对路径)
  * 返回:文件生成时间秒数,文件不存在返回0
  */
function getFileCreateTime( $fileName ) {
  if( ! trim($fileName) ) return 0;
  if( file_exists( $fileName ) ) {
  return intval(filemtime( $fileName ));
  }else return 0;
} 
/*
  * 保存文件
  * string $fileName 文件名(含相对路径)
  * string $text 文件内容
  * 返回:成功返回ture,失败返回false
  */
function saveFile($fileName, $text) {
  if( ! $fileName || ! $text ) return false;
  if( $this->makeDir( dirname( $fileName ) ) ) {
  if( $fp = fopen( $fileName, "w" ) ) {
  if( @fwrite( $fp, $text ) ) {
  fclose($fp);
  return true;
  }else {
  fclose($fp);
  return false;
  }
  }
  }
  return false;
}
/*
  * 连续建目录
  * string $dir 目录字符串
  * int $mode 权限数字
  * 返回:顺利创建或者全部已建返回true,其它方式返回false
  */
function makeDir( $dir, $mode = "0777" ) {
  if( ! $dir ) return 0;
  $dir = str_replace( "\\", "/", $dir );
  $mdir = "";
  foreach( explode( "/", $dir ) as $val ) {
  $mdir .= $val."/";
  if( $val == ".." || $val == "." || trim( $val ) == "" ) continue;
  if( ! file_exists( $mdir ) ) {
  if(!@mkdir( $mdir, $mode )){
  return false;
  }
  }
  }
  return true;
}
}
?>
Copy after login

使用该缓存类的时候可将以上代码保存为cache.php,具体用法如下所示:

include( "cache.php" );$cache = new cache(30);$cache->cacheCheck();echo date("Y-m-d H:i:s");$cache->caching();
Copy after login

转载地址:https://www.cnblogs.com/zhangmiaomiao/p/6013314.html

PHP中常用的缓存技术归类:

1、全页面静态化缓存

也就是将页面全部生成html静态页面,用户访问时直接访问的静态页面,而不会去走php服务器解析的流程。此种方式,在CMS系统中比较常见,比如dedecms;

一种比较常用的实现方式是用输出缓存:

Ob_start()
******要运行的代码*******
$content = Ob_get_contents();
****将缓存内容写入html文件*****
Ob_end_clean();

2、页面部分缓存

该种方式,是将一个页面中不经常变的部分进行静态缓存,而经常变化的块不缓存,最后组装在一起显示;可以使用类似于ob_get_contents 的方式实现,也可以利用类似ESI之类的页面片段缓存策略,使其用来做动态页面中相对静态的片段部分的缓存(ESI技术,请baidu,此处不详讲)。

该种方式可以用于如商城中的商品页;

3、数据缓存

顾名思义,就是缓存数据的一种方式;比如,商城中的某个商品信息,当用商品id去请求时,就会得出包括店铺信息、商品信息等数据,此时就可以将这些 数据缓存到一个php文件中,文件名包含商品id来建一个唯一标示;下一次有人想查看这个商品时,首先就直接调这个文件里面的信息,而不用再去数据库查 询;其实缓存文件中缓存的就是一个php数组之类;

Ecmall商城系统里面就用了这种方式;

4、查询缓存

其实这跟数据缓存是一个思路,就是根据查询语句来缓存;将查询得到的数据缓存在一个文件中,下次遇到相同的查询时,就直接先从这个文件里面调数据,不会再去查数据库;但此处的缓存文件名可能就需要以查询语句为基点来建立唯一标示;

按时间变更进行缓存

其实,这一条不是真正的缓存方式;上面的2、3、4的缓存技术一般都用到了时间变更判断;就是对于缓存文件您需要设一个有效时间,在这个有效时间 内,相同的访问才会先取缓存文件的内容,但是超过设定的缓存时间,就需要重新从数据库中获取数据,并生产最新的缓存文件;比如,我将我们商城的首页就是设 置2个小时更新一次;

5、按内容变更进行缓存

这个也并非独立的缓存技术,需结合着用;就是当数据库内容被修改时,即刻更新缓存文件;

比如,一个人流量很大的商城,商品很多,商品表必然比较大,这表的压力也比较重;我们就可以对商品显示页进行页面缓存;

当商家在后台修改这个商品的信息时,点击保存,我们同时就更新缓存文件;那么,买家访问这个商品信息时,实际上访问的是一个静态页面,而不需要再去访问数据库;

试想,如果对商品页不缓存,那么每次访问一个商品就要去数据库查一次,如果有10万人在线浏览商品,那服务器压力就大了;

6、内存式缓存

提到这个,可能大家想到的首先就是Memcached;memcached是高性能的分布式内存缓存服务器。 一般的使用目的是,通过缓存数据库查询结果,减少数据库访问次数,以提高动态Web应用的速度、 提高可扩展性。

它就是将需要缓存的信息,缓存到系统内存中,需要获取信息时,直接到内存中取;比较常用的方式就是 key–>value方式;

$memcachehost = '192.168.6.191';
$memcacheport = 11211;
$memcachelife = 60;
$memcache = new Memcache;
$memcache->connect($memcachehost,$memcacheport) or die ("Could not connect");
     $memcache->set('key','缓存的内容');
     $get = $memcache->get($key);       //获取信息
?>

7、apache缓存模块

apache安装完以后,是不允许被cache的。如果外接了cache或squid服务器要求进行web加速的话,就需要在htttpd.conf里进行设置,当然前提是在安装apache的时候要激活mod_cache的模块。

安装apache时:./configure –enable-cache –enable-disk-cache –enable-mem-cache

8、php APC缓存扩展

Php有一个APC缓存扩展,windows下面为php_apc.dll,需要先加载这个模块,然后是在php.ini里面进行配置:

[apc]
extension=php_apc.dll
apc.rfc1867 = on
upload_max_filesize = 100M
post_max_size = 100M
apc.max_file_size = 200M
upload_max_filesize = 10 00M
post_max_size = 1000M
max_execution_time = 600; Maximum time (seconds) for each PHP page to run, default 30 seconds
max_input_time = 600; Maximum time required for each PHP page to receive data, default 60
Memory_limit = 128M; The maximum memory consumed by each PHP page, the default is 8M

9, Opcode cache

We know that the execution process of PHP can be shown in the following figure:

First the PHP code is parsed into Tokens, then compiled into Opcode code, and finally the Opcode code is executed and the result is returned; therefore, for the same PHP file, the first run can Cache its Opcode code. The next time you execute this page, you will directly find the cached Opcode code and execute the last step directly, without the need for intermediate steps.

The more well-known ones are XCache, Turck MM Cache, PHP Accelerator, etc.

Related recommendations:

Steps to implement PHP cache optimization using memcached and xcache

Several major PHP caching technologies that must be obtained

Instructions for using the php cache file extracted from the CI framework

The above is the detailed content of How to implement PHP cache class. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!