1: <?php
 2:     require_once('Cache/Lite.php'); // PEAR::Cache_Lite
 3:     
 4:     /**
 5:      * @author Jan "johno" Suchal
 6:      * @version 0.1
 7:      **/
 8:     class ServerClientCache {
 9:         private static $cache;
10:         private static $id;
11:         private static $group;
12:         
13:         public static function init($options = array()) {
14:             self::$cache = new Cache_Lite($options);
15:         }
16:         
17:         public static function get($id, $group = 'default') {
18:             self::$id = $id;
19:             self::$group = $group;
20:             $data = self::$cache->get($id, $group, true);
21:             if($data === false) {
22:                 // data is not cached on server
23:                 return false;
24:             } else {
25:                 // data is cached on server
26:                 $serverLastModified = self::$cache->lastModified();
27:                 $headers = apache_request_headers();
28:                 if(array_key_exists('If-Modified-Since', $headers)) {
29:                     // client has something in cache
30:                     $clientLastModified = strtotime($headers['If-Modified-Since']);
31:                     if($clientLastModified >= $serverLastModified) {
32:                         // client cache is up-to-date
33:                         header('HTTP/1.1 304 Not Modified'); 
34:                         return true;
35:                     }
36:                 }
37:                 // client cache is obsolete or not used
38:                 header('Last-Modified: '.gmdate('D, d M Y H:i:s', $serverLastModified).' GMT');
39:                 echo $data;
40:                 return true;
41:             }
42:         }
43:         
44:         public static function saveAndOutput($data) {
45:             self::$cache->save($data, self::$id, self::$group);
46:             $serverLastModified = self::$cache->lastModified();
47:             header('Last-Modified: '.gmdate('D, d M Y H:i:s', $serverLastModified).' GMT');
48:             echo $data;
49:         }
50:         
51:         public static function clean($group = null) {
52:             self::$cache->clean($group);
53:         }
54:         
55:         public static function remove($id, $group = 'default') {
56:             self::$cache->remove($id, $group);
57:         }
58:     }
59: ?>