Quick Search:

View

Revision:

Diff

Diff from 1497 to:

Annotations

Annotate by Age | Author | Mixed | None
/fisheye/browse/osCommerce/branches/hpdl/oscommerce/includes/classes/cache.php

Annotated File View

hpdl
1
1 <?php
2 /*
hpdl
153
3   $Id: cache.php 1497 2007-03-29 13:40:05Z hpdl $
hpdl
1
4
5   osCommerce, Open Source E-Commerce Solutions
6   http://www.oscommerce.com
7
8   Copyright (c) 2004 osCommerce
9
hpdl
1497
10   This program is free software; you can redistribute it and/or modify
11   it under the terms of the GNU General Public License v2 (1991)
12   as published by the Free Software Foundation.
hpdl
1
13
14   Class usage examples:
15
16   - Caching HTML:
17     if ($osC_Cache->read('key', 60) === false) {
18       $osC_Cache->startBuffer();
19       ------ PHP/HTML LOGIC HERE ------
20       $osC_Cache->stopBuffer();
21     }
22
23     echo $osC_Cache->getCache();
24
25   - Caching data (in memory):
26     if ($osC_Cache->read('key', 60) {
27       $variable = $osC_Cache->getCache();
28     } else {
29       $variable = array('some', 'data');
30
31       $osC_Cache->writeBuffer($variable);
32     }
33 */
34
35   class osC_Cache {
36     var $cached_data,
37         $cache_key;
38
39     function write($key, &$data) {
40       $filename = DIR_FS_WORK . $key . '.cache';
41
42       if ($fp = @fopen($filename, 'w')) {
43         flock($fp, 2); // LOCK_EX
44         fputs($fp, serialize($data));
45         flock($fp, 3); // LOCK_UN
46         fclose($fp);
47
48         return true;
49       }
50
51       return false;
52     }
53
54     function read($key, $expire = 0) {
55       $this->cache_key = $key;
56
57       $filename = DIR_FS_WORK . $key . '.cache';
58
59       if (file_exists($filename)) {
60         $difference = floor((time() - filemtime($filename)) / 60);
61
62         if ( ($expire == '0') || ($difference < $expire) ) {
63           if ($fp = @fopen($filename, 'r')) {
64             $this->cached_data = unserialize(fread($fp, filesize($filename)));
65
66             fclose($fp);
67
68             return true;
69           }
70         }
71       }
72
73       return false;
74     }
75
76     function &getCache() {
77       return $this->cached_data;
78     }
79
80     function startBuffer() {
81       ob_start();
82     }
83
84     function stopBuffer() {
85       $this->cached_data = ob_get_contents();
86
87       ob_end_clean();
88
89       $this->write($this->cache_key, $this->cached_data);
90     }
91
92     function writeBuffer(&$data) {
93       $this->cached_data = $data;
94
95       $this->write($this->cache_key, $this->cached_data);
96     }
97
98     function clear($key) {
99       $key_length = strlen($key);
100
101       $d = dir(DIR_FS_WORK);
102
103       while ($entry = $d->read()) {
104         if ((strlen($entry) >= $key_length) && (substr($entry, 0, $key_length) == $key)) {
105           @unlink(DIR_FS_WORK . $entry);
106         }
107       }
108
109       $d->close();
110     }
111   }
112 ?>