http://www.oschina.net/code/snippet_162279_6098

<?php
class cache
{  
    private static $_instance = null;
 
    protected $_options = array(
        'cache_dir'        => "./",
        'file_name_prefix' => 'cache',
        'mode'            => '1', //mode 1 为serialize model 2为保存为可执行文件
    ); 
     
    /**
     * 得到本类实例
     *
     * @return Ambiguous
     */
    public static function getInstance()
    {
        if(self::$_instance === null)
        {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
     
    /**
     * 得到缓存信息
     *
     * @param string $id
     * @return boolean|array
     */
    public static function get($id)
    {
        $instance = self::getInstance();
         
        //缓存文件不存在
        if(!$instance->has($id))
        {
            return false;
        }
         
        $file = $instance->_file($id);
         
        $data = $instance->_fileGetContents($file);
         
        if($data['expire'] == 0 || time() < $data['expire'])
        {
            return $data['contents'];
        }
        return false;
    }
     
    /**
     * 设置一个缓存
     *
     * @param string $id   缓存id
     * @param array  $data 缓存内容
     * @param int    $cacheLife 缓存生命 默认为0无限生命
     */
    public static function set($id, $data, $cacheLife = 0)
    {
        $instance = self::getInstance();
         
        $time = time();
        $cache         = array();
        $cache['contents'] = $data;
        $cache['expire']   = $cacheLife === 0 ? 0 : $time + $cacheLife;
        $cache['mtime']    = $time;
         
        $file = $instance->_file($id);
         
        return $instance->_filePutContents($file, $cache);
    }
     
    /**
     * 清除一条缓存
     *
     * @param string cache id   
     * @return void
     */  
    public static function delete($id)
    {
        $instance = self::getInstance();
         
        if(!$instance->has($id))
        {
            return false;
        }
        $file = $instance->_file($id);
        //删除该缓存
        return unlink($file);
    }
     
    /**
     * 判断缓存是否存在
     *
     * @param string $id cache_id
     * @return boolean true 缓存存在 false 缓存不存在
     */
    public static function has($id)
    {
        $instance = self::getInstance();
        $file     = $instance->_file($id);
         
        if(!is_file($file))
        {
            return false;
        }
        return true;
    }
     
    /**
     * 通过缓存id得到缓存信息路径
     * @param string $id
     * @return string 缓存文件路径
     */
    protected function _file($id)
    {
        $instance  = self::getInstance();
        $fileNmae  = $instance->_idToFileName($id);
        return $instance->_options['cache_dir'] . $fileNmae;
    }  
     
    /**
     * 通过id得到缓存信息存储文件名
     *
     * @param  $id
     * @return string 缓存文件名
     */
    protected function _idToFileName($id)
    {
        $instance  = self::getInstance();
        $prefix    = $instance->_options['file_name_prefix'];
        return $prefix . '---' . $id;
    }
     
    /**
     * 通过filename得到缓存id
     *
     * @param  $id
     * @return string 缓存id
     */
    protected function _fileNameToId($fileName)
    {
        $instance  = self::getInstance();
        $prefix    = $instance->_options['file_name_prefix'];
        return preg_replace('/^' . $prefix . '---(.*)$/', '$1', $fileName);
    }
     
    /**
     * 把数据写入文件
     *
     * @param string $file 文件名称
     * @param array  $contents 数据内容
     * @return bool
     */
    protected function _filePutContents($file, $contents)
    {
        if($this->_options['mode'] == 1)
        {
            $contents = serialize($contents);
        }
        else
        {
            $time = time();
            $contents = "<?php\n".
                    " // mktime: ". $time. "\n".
                    " return ".
                    var_export($contents, true).
                    "\n?>";
        }
         
        $result = false;
        $f = @fopen($file, 'w');
        if ($f) {
            @flock($f, LOCK_EX);
            fseek($f, 0);
            ftruncate($f, 0);
            $tmp = @fwrite($f, $contents);
            if (!($tmp === false)) {
                $result = true;
            }
            @fclose($f);
        }
        @chmod($file,0777);
        return $result;            
    }
     
    /**
     * 从文件得到数据
     *
     * @param  sring $file
     * @return boolean|array
     */
    protected function _fileGetContents($file)
    {
        if(!is_file($file))
        {
            return false;
        }
         
        if($this->_options['mode'] == 1)
        {
            $f = @fopen($file, 'r');
            @$data = fread($f,filesize($file));
            @fclose($f);
            return unserialize($data);
        }
        else
        {
            return include $file;
        }
    }
     
    /**
     * 构造函数
     */
    protected function __construct()
    {
     
    }
     
    /**
     * 设置缓存路径
     *
     * @param string $path
     * @return self
     */
    public static function setCacheDir($path)
    {
        $instance  = self::getInstance();
        if (!is_dir($path)) {
            exit('file_cache: ' . $path.' 不是一个有效路径 ');
        }
        if (!is_writable($path)) {
            exit('file_cache: 路径 "'.$path.'" 不可写');
        }
     
        $path = rtrim($path,'/') . '/';
        $instance->_options['cache_dir'] = $path;
         
        return $instance;
    }
     
    /**
     * 设置缓存文件前缀
     *
     * @param srting $prefix
     * @return self
     */
    public static function setCachePrefix($prefix)
    {
        $instance  = self::getInstance();
        $instance->_options['file_name_prefix'] = $prefix;
        return $instance;
    }
     
    /**
     * 设置缓存存储类型
     *
     * @param int $mode
     * @return self
     */
    public static function setCacheMode($mode = 1)
    {
        $instance  = self::getInstance();
        if($mode == 1)
        {
            $instance->_options['mode'] = 1;
        }
        else
        {
            $instance->_options['mode'] = 2;
        }
         
        return $instance;
    }
     
    /**
     * 删除所有缓存
     * @return boolean
     */
    public static function flush()
    {
        $instance  = self::getInstance();
        $glob = @glob($instance->_options['cache_dir'] . $instance->_options['file_name_prefix'] . '--*');
         
        if(empty($glob))
        {
            return false;
        }
         
        foreach ($glob as $v)
        {
            $fileName = basename($v);
            $id $instance->_fileNameToId($fileName);
            $instance->delete($id);
        }
        return true;
    }
}
 
/* 初始化设置cache的配置信息什么的 */
cache::setCachePrefix('core'); //设置缓存文件前缀
cache::setCacheDir('./cache'); //设置存放缓存文件夹路径
 
//模式1 缓存存储方式
//a:3:{s:8:"contents";a:7:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:34;i:4;i:5;i:5;i:6;i:6;i:6;}s:6:"expire";i:0;s:5:"mtime";i:1318218422;}
//模式2 缓存存储方式
/*
 <?php
 // mktime: 1318224645
 return array (
  'contents' =>
  array (
    0 => 1,
    1 => 2,
    2 => 3,
    3 => 34,
    4 => 5,
    5 => 6,
    6 => 6,
  ),
  'expire' => 0,
  'mtime' => 1318224645,
)
?>
 *
 *
 */
cache::setCacheMode('2');
 
if(!$row = cache::get('zj2'))
{
     
    $array = array(1,2,3,34,5,6,6);
    $row = cache::set('zj2',$array);
}
// cache::flush(); 清空所有缓存
 
print_r($row);
    
 

[2].[代码] 文件缓存 class 跳至 [1] [2] [3] [4] [5] [6]

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
<?php
/**
 * 文件缓存类
 * @author  xiaojiong & 290747680@qq.com
 * @date 2011-08-17
 */
class cache
{
    const FILE_LIFE_KEY = 'FILE_LIFE_KEY';
     
    const CLEAR_ALL_KEY = 'CLEAR_ALL';
     
    static $_instance = null;
     
    protected $_options = array(
        'cache_dir' => './cache',
        'file_locking' => true,
        'file_name_prefix' => 'cache',
        'cache_file_umask' => 0777,
        'file_life'  => 100000
    );
     
    static function &getInstance($options = array())
    {
        if(self::$_instance === null)
        {
            self::$_instance = new self($options);
        }  
        return self::$_instance;
    }
     
    /**
     * 设置参数
     * @param  array $options 缓存参数
     * @return void
     */
    static function &setOptions($options = array())
    {
            return self::getInstance($options);
    }
     
    /**
     * 构造函数
     * @param  array $options 缓存参数
     * @return void
     */
    private function __construct($options = array())
    {      
        if ($this->_options['cache_dir'] !== null) {
             
            $dir = rtrim($this->_options['cache_dir'],'/') . '/';
            $this->_options['cache_dir'] = $dir;
             
            if (!is_dir($this->_options['cache_dir'])) {
                mkdir($this->_options['cache_dir'],0777,TRUE);
            }
            if (!is_writable($this->_options['cache_dir'])) {
                exit('file_cache: 路径 "'. $this->_options['cache_dir'] .'" 不可写');
            }
          
        } else {
           exit('file_cache: "options" cache_dir 不能为空 ');
        }
    }
 
    /**
     * 设置缓存路径
     * @param  string  $value
     * @return void
     */
    static function setCacheDir($value)
    {
        $self = & self::getInstance();
         
        if (!is_dir($value)) {
            exit('file_cache: ' . $value.' 不是一个有效路径 ');
        }
        if (!is_writable($value)) {
            exit('file_cache: 路径 "'.$value.'" 不可写');
        }
     
        $value = rtrim($this->_options['cache_dir'],'/') . '/';
         
        $self->_options['cache_dir'] = $value;
    }
     
    /**
     * 存入缓存数据
     * @param  array  $data          放入缓存的数据
     * @param  string $id            缓存id(又名缓存识别码)
     * @param  cache_life            缓存时间
     * @return boolean True if no problem
     */
    static function save($data, $id = null, $cache_life = null)
    {
        $self = & self::getInstance();
        if (!$id) {
            if ($self->_id) {
                $id = $self->_id;
            } else {
                exit('file_cache:save() id 不能为空!');
            }
        }
        $time = time();
         
        if($cache_life) {
            $data[self::FILE_LIFE_KEY] = $time + $cache_life;
        }
        elseif
        ($cache_life != 0){
            $data[self::FILE_LIFE_KEY] = $time + $self->_options['file_life'];
        }
         
        $file = $self->_file($id);
         
        $data = "<?php\n".
                " // mktime: ". $time. "\n".
                " return ".
                var_export($data, true).
                "\n?>"
                ;
         
        $res = $self->_filePutContents($file, $data);
        return $res;
    }
     
     
    /**
     * 得到缓存信息
     *
     * @param  string  $id  缓存id
     * @return string|array 缓存数据
     */
    static function load($id)
    {
        $self = & self::getInstance();
        $time = time();
        //检测缓存是否存在
        if (!$self->test($id)) {
            // The cache is not hit !
            return false;
        }
         
        //全部清空识别文件
        $clearFile = $self->_file(self::CLEAR_ALL_KEY);
         
        $file = $self->_file($id);
         
        //判断缓存是否已被全部清除
        if(is_file($clearFile) && filemtime($clearFile) > filemtime($file))
        {
            return false;
        }
        
        $data = $self->_fileGetContents($file);
        if(empty($data[self::FILE_LIFE_KEY]) || $time < $data[self::FILE_LIFE_KEY]) {
            unset($data[self::FILE_LIFE_KEY]);
            return $data;          
        }
        return false;
    }   
     
    /**
     * 写入缓存文件
     *
     * @param  string $file   缓存路径
     * @param  string $string 缓存信息
     * @return boolean true 成功
     */
    protected function _filePutContents($file, $string)
    {
        $self = & self::getInstance();
        $result = false;
        $f = @fopen($file, 'ab+');
        if ($f) {
            if ($self->_options['file_locking']) @flock($f, LOCK_EX);
            fseek($f, 0);
            ftruncate($f, 0);
            $tmp = @fwrite($f, $string);
            if (!($tmp === false)) {
                $result = true;
            }
            @fclose($f);
        }
        @chmod($file, $self->_options['cache_file_umask']);
        return $result;
    }
     
    /**
     * 格式化后的缓存文件路径
     *
     * @param  string $id 缓存id
     * @return string 缓存文件名(包括路径)
     */
    protected function _file($id)
    {
        $self = & self::getInstance();
        $fileName = $self->_idToFileName($id);
        return $self->_options['cache_dir'] . $fileName;
    }   
     
    /**
     * 格式化后的缓存文件名字
     *
     * @param  string $id 缓存id
     * @return string 缓存文件名
     */
    protected function _idToFileName($id)
    {
        $self = & self::getInstance();
        $self->_id = $id;
        $prefix = $self->_options['file_name_prefix'];
        $result = $prefix . '---' . $id;
        return $result;
    }  
     
    /**
     * 判断缓存是否存在
     *
     * @param  string $id Cache id
     * @return boolean True 缓存存在 False 缓存不存在
     */
    static function test($id)
    {
        $self = & self::getInstance();
        $file = $self->_file($id);
         
        if (!is_file($file)) {
            return false;
        }
         
        return true;
    }
     
    /**
     * 得到缓存信息
     *
     * @param  string $file 缓存路径
     * @return string 缓存内容
     */
    protected function _fileGetContents($file)
    {
        if (!is_file($file)) {
            return false;
        }
        return include $file;
    }    
     
    /**
     * 清除所有缓存
     *
     * @return void
     */   
    static function clear()
    {
        $self = & self::getInstance();
        $self->save('CLEAR_ALL',self::CLEAR_ALL_KEY);   
    }  
     
    /**
     * 清除一条缓存
     *
     * @param string cache id   
     * @return void
     */  
    static function del($id)
    {
        $self = & self::getInstance();
        if(!$self->test($id)){
            // 该缓存不存在
            return false;
        }
        $file = $self->_file($id);
        return unlink($file);
    }  
}
 

[3].[代码] 存入数据 跳至 [1] [2] [3] [4] [5] [6]

1
2
3
4
5
6
7
8
9
10
11
<?php
$config = array(
    'name' => 'xiaojiong',
    'qq'   => '290747680',
    'age'  => '20',
);
 
//第一个参数 缓存data
//第二个参数 缓存id
//第三个参数 cache_life 0 永不过期(cache::clear()清空所有除外) 默认cache_life 为option_cache_life
cache::save($config,'config',0);
 

[4].[代码] 载入数据 跳至 [1] [2] [3] [4] [5] [6]

1
2
3
<?php
//只有一个参数 cache_id
$config = cache::load('config');
 

[5].[代码] 清空缓存 跳至 [1] [2] [3] [4] [5] [6]

1
2
3
4
5
<?php
//清空指定缓存
cache::del('config');
//清空所有缓存
cache::clear();
 

[6].[代码] cache信息配置 跳至 [1] [2] [3] [4] [5] [6]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//在执行所有cache_func前调用
 
$_options = array(
    'cache_dir' => './cache', //缓存文件目录
    'file_name_prefix' => 'cache',//缓存文件前缀
    'file_life'  => 100000, //缓存文件生命
);
cache::setOptions($options);
 
//再执行 就会按着新配置信息执行,否则是默认信息
cache::save($arr,'arr');
 
 
//就是这个方法 貌似不合理 望大家指点

php 文件缓存的更多相关文章

  1. PHP文件缓存实现

    有些时候,我们不希望使用redis等第三方缓存,使得系统依赖于其他服务.这时候,文件缓存会是一个不错的选择. 我们需要文件缓存实现哪些共更能: 功能实现:get.set.has.increment.d ...

  2. 高性能文件缓存key-value存储—Redis

    1.高性能文件缓存key-value存储-Memcached 2.ASP.NET HttpRuntime.Cache缓存类使用总结 备注:三篇博文结合阅读,简单理解并且使用,如果想深入学习,请多参考文 ...

  3. [Android]异步加载图片,内存缓存,文件缓存,imageview显示图片时增加淡入淡出动画

    以下内容为原创,欢迎转载,转载请注明 来自天天博客:http://www.cnblogs.com/tiantianbyconan/p/3574131.html  这个可以实现ImageView异步加载 ...

  4. php使用文件缓存

    使用php读取mysql中的数据很简单,数据量不大的时候,mysql的性能还是不错的.但是有些查询可能比较耗时,这时可以把查询出的结果,缓存起来,减轻mysql的查询压力. 缓存的方法有几种:使用me ...

  5. 高性能文件缓存key-value存储—Memcached

    1.高性能文件缓存key-value存储—Redis 2.ASP.NET HttpRuntime.Cache缓存类使用总结 备注:三篇博文结合阅读,简单理解并且使用,如果想深入学习,请多参考文章中给出 ...

  6. htaccess 增加静态文件缓存和压缩

    增加图片视频等静态文件缓存: <FilesMatch ".(flv|gif|jpg|jpeg|png|ico|swf)$"> Header set Cache-Cont ...

  7. PHP文件缓存与memcached缓存 相比 优缺点是什么呢【总结】

    如果不考虑其他任何问题,只比较速度的话,那肯定是mem快,但他们各有优缺点.文件缓存优点:1.由于现在的硬盘都非常大,所有如果是大数据的时候,放硬盘里就比较合适,比如做一个cms网站,网站里有10万篇 ...

  8. app缓存设计-文件缓存

    采用缓存,可以进一步大大缓解数据交互的压力,又能提供一定的离线浏览.下边我简略列举一下缓存管理的适用环境: 1. 提供网络服务的应用 2. 数据更新不需要实时更新,哪怕是3-5分钟的延迟也是可以采用缓 ...

  9. phalcon: 缓存片段,文件缓存,memcache缓存

    几种缓存,需要用到前端配置,加后端实例配合着用 片段缓存: public function indexAction() { //渲染页面 $this->view->setTemplateA ...

  10. js和HTML结合(补充知识:如何防止文件缓存的js代码)

    来自<javascript高级程序设计 第三版:作者Nicholas C. Zakas>的学习笔记(二) 使用html标签<script>可以把js嵌入到html页面中,让脚本 ...

随机推荐

  1. Gym 100827G Number Game (博弈)

    Number Game Alice and Bob are playing a game on a line of N squares. The line is initially populated ...

  2. 局域网Internet的共享

    局域网接入Internet,之后,在服务器安装共享代理软件,可以使客户机通过代理软件接入Internet. 局域网接入Internet 而目前几乎所有的浏览器.下载软件.信件收发软件都支持代理服务器. ...

  3. 优步(UBER)发布2016年春节出境游出行报告

    滴快车单单2.5倍,注册地址:http://www.udache.com/ 如何注册Uber司机(全国版最新最详细注册流程)/月入2万/不用抢单:http://www.cnblogs.com/mfry ...

  4. C/S 和 B/S 模式的区别与联系

    如果要比较两种事物之间的相同点和不同点,首先,我们要分别对这两种事物有一个最基本的了解. 一.C/S与B/S的定义 C/S (Client/Server)结构,即大家熟知的客户机和服务器结构.它是软件 ...

  5. CSS构造颜色、背景与图像

    设定颜色 背景使用 图像使用 1.设定颜色 红色的几种合法定义;     #f00;     #ff0000;     Red;     Rgb(255,0,0);     Rgb(100%,0%,0 ...

  6. git 快速入门(二)

    一.引子 git代码托管的优秀工具之一, 其工作原理和svn截然不同.一旦拥有主干master分支权限, 只要在本地拉取主干分支, 可以随时随地切换分支. 它拥有众多优点,eg :支持在断网的情况下, ...

  7. 今天写一些 有关iOS 多图片组合 成一张图片的问题。保持原像素不变

    1.要求:服务器给一张图片模板,要在模版上镂空,然后添加一些别的图片,然后组合成一张图,这个模版的像素 不是固定的,有可能比 当前手机屏幕大.所以,在组合截图的时候,有一定的要求. 贴代码: /** ...

  8. JFinal tomcat配置根路径(包括windows和linux)

    http://my.oschina.net/u/173975/blog/350666 jfinal的demo直接部署到tomcat上,会由于路径问题导致资源加载不到,路径跳转不正确等问题,解决办法如下 ...

  9. 基于新浪sae使用php生成图片发布图文微博

    1.生成图片的代码: <?php header ("Content-type: image/png"); mb_internal_encoding("UTF-8&q ...

  10. Android在MediaMuxer和MediaCodec用例 - audio+video

    在Android多媒体类,MediaMuxer和MediaCodec这是一个相对年轻,他们是JB 4.1和JB 4.3据介绍. 前者被用来产生一个混合的音频和视频的多媒体文件.的缺点是,现在可以只支持 ...