php怎样数据缓存文件,php数据缓存到文件类设计

本文介绍了一种使用PHP编写的自定义缓存类Cache_Filesystem,通过文件系统实现数据的存储和读取,重点讲解了set、get和clear方法的实现。实例演示了如何在电商项目中使用缓存提高数据访问效率。
摘要由CSDN通过智能技术生成

// 自定义缓存类

class Cache_Filesystem {

// 缓存写保存

function set ($key, $data, $ttl) {

//打开文件为读/写模式

$h = fopen($this->get_filename($key), ‘a+‘);

if (!$h) throw new Exception("Could not write to cache");

flock($h, LOCK_EX); //写锁定,在完成之前文件关闭不可再写入

fseek($h, 0); // 读到文件头

ftruncate($h, 0); //清空文件内容

// 根据生存周期$ttl写入到期时间

$data = serialize(array(time()+$ttl, $data));

if (fwrite($h, $data) === false) {

throw new Exception(‘Could not write to cache‘);

}

fclose($h);

}

// 读取缓存数据,如果未取出返回失败信息

function get ($key) {

$filename = $this->get_filename($key);

if ( !file_exists( $filename ) ) {

return false;

}

$h = fopen($filename, ‘r‘);

if (!$h) return false;

// 文件读取锁定

flock($h, LOCK_SH);

$data = file_get_contents($filename);

fclose($h);

$data = @unserialize($data);

if ( !$data ) {

// 如果反序列化失败,则彻底删除该文件

unlink($filename);

return false;

}

if (time() > $data[0]) {

// 如果缓存已经过期,则删除文件

unlink($filename);

return false;

}

}

// 清除缓存

function clear ( $key ) {

$filename = $this->get_filename($key);

if (file_exists($filename)) {

return unlink($filename);

} else {

return false;

}

}

// 获取缓存文件

private function get_filename ($key) {

return ‘./cache/‘ . md5($key);

}

}

调用

require ‘./4.3-cache_class.php‘;

// 创建新对象

$cache = new Cache_Filesystem();

function getUsers () {

global $cache;

// 自定义一个缓存key唯一标识

$key = ‘getUsers:selectAll‘;

// 检测数据是否缓存

if ( !$data = $cache->get( $key ) ) {

// 如果没有缓存,则获取新数据

$db_host = ‘localhost‘;

$db_user = ‘root‘;

$db_password = ‘root‘;

$database = ‘ecshop_test‘;

$conn = mysql_connect( $db_host, $db_user, $db_password);

mysql_select_db($database);

//执行sql查询

$result = mysql_query("select * from ecs_users");

$data = array();

// 将获取到的数据放入数组$data中

while ( $row = mysql_fetch_assoc($result)) {

$data[] = $row;

}

// 保存该数据到缓存中,生存周期为10分钟

$cache->set($key, $data, 10);

}

return $data;

}

try {

$users = getUsers();

print_r($users);

$key = ‘getUsers:selectAll‘;

//$cache->clear($key);

} catch (Exception $e) {

print $e->getMessage();

}

原文:http://www.cnblogs.com/chengzhi59/p/7419523.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值