PHP数据缓存

缓存技术是web开发用来提高网站访问速度和减缓服务器压力的的重要手段之一,缓存主要分为页面缓存和数据缓存,一般情况下首页都采用页面缓存技术,其他的一些页面采用数据缓存比较多。下面贴上最近用php实现的数据缓存代码

cache.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?php
class Cache {
private $cache_path;//path for the cache
private $cache_expire;//seconds that the cache expires
//cache constructor, optional expiring time and cache path
function __construct($exp_time=3600,$path=”cache/”){
$this->cache_expire=$exp_time;
$this->cache_path=$path;
}
//returns the filename for the cache
private function fileName($key){
return $this->cache_path.md5($key);
}
//creates new cache files with the given data, $key== name of the cache, data the info/values to store
public function put($key, $data){
$values = serialize($data);
$filename = $this->fileName($key);
$file = fopen($filename, ‘w’);
if ($file){//able to create the file
fwrite($file, $values);
fclose($file);
return true;
}
else return false;
}
//returns cache for the given key
public function get($key){
$filename = $this->fileName($key);
if (!file_exists($filename) || !is_readable($filename)){//can’t read the cache
return false;
}
if ( time() < (filemtime($filename) + $this->cache_expire) ) {//cache for the key not expired
$file = fopen($filename, “r”);// read data file
if ($file){//able to open the file
$data = fread($file, filesize($filename));
fclose($file);
return unserialize($data);//return the values
}
else return false;
}
else return false;//was expired you need to create new
}
}
?>

调用方法(完整列子):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function get_cache_data($key){
//从缓存从读取键值 $key 的数据
$values = $this->data_cache->get($key);
//返回读取结果
return $values;
}
function put_cache_data($key,$data){
//insert code here…
//写入键值 $key 的数据
$is_write = $this->data_cache->put($key, $data);
return $is_write;
}
/**
* 最新成交列表
*/
public function get_lastbargainlist()
{
$list_xml = $this->get_cache_data(“lastbargainlist”);
if(!$list_xml){
$list_xml = $this->soap_client->doRequest($this->request_xml(“HS”,”lastbargainlist”));
if(!$this->put_cache_data(“lastbargainlist”,$list_xml)){
// echo “<script> alert(‘失败!’); </script>”;
}
}
$list_arr = simplexml_load_string($list_xml);
return $list_arr;
}

实现页面缓存需要用到 ob_start ob_get_content ob_clean等函数,下次有需要的时候再去实现