php简单数据缓存类

本文详细介绍了如何在公司手机触屏站中实现数据缓存,通过编写一个简单的数据缓存类来优化网站性能。通过设置是否开启缓存、缓存目录和缓存时间,有效地减少了对数据库的频繁访问,提高了页面加载速度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

公司手机触屏站 ,由于页面图片太多,所以需要做数据缓存,就随便写一个数据缓存类。

直接贴代码

<?php
/**
*
* fianl_m@foxmail.com
* 缓存类
* 把数据查询出,并序列化写入文件
**/
class Cache{

function __construct($config){
//定义是否开启缓存
$this->is_cache=$config['is_cache'];
//定义缓存目录
$this->cache_file=$config['cache_file'];
//定义缓存时间
$this->cache_time=$config['cache_time'];


}

//读取缓存文件
public function open($name){

$arr=array();
$filename=$this->cache_file.$name;
$status=filemtime($filename)+$this->cache_time>time();//定义缓存时间
if( file_exists($filename) && $status && $this->is_cache){
$content=file_get_contents($filename);//读取缓存文件
$arr=unserialize($content);
return $arr;
}else{
return false;
}

}
//写入缓存文件
public function write($name,$data=array()){
$filename=$this->cache_file.$name;
$content=serialize($data);
file_put_contents($filename, $content);//写入缓存文件

}

 

 

}


?>

 

其实无非就是,把select的数组  然后序列化 放进文本中 然后读出来。

使用方法

//定义缓存是否开启
require('cache.class.php');
$config=array(
'is_cache'=>1,//是否开启缓存
'cache_file'=>'./cache/',//缓存文件夹
'cache_time'=>'60',//缓存时间
);
$cache=new Cache($config);

//打开缓存,传入缓存文件名字

$row=$cache->open($filename);

//写入缓存传入文件名字  和数据(数组)

$cache->write($filename,$data);

 

ps:有不懂的 可以给我留言  非囍勿喷,大神绕过,菜鸟学习!

 

转载于:https://www.cnblogs.com/padog/p/4545884.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值