00001 <?php
00013 class Cache_SHM extends Cache
00014 {
00015 var $shmkey;
00016 var $shmid;
00017 var $memsize = CACHE_SHM_SIZE;
00018
00022 function Cache_SHM()
00023 {
00024 $this->Cache();
00025
00026
00027 $this->shmkey = ftok(DIR_FS_BASE.DS.'index.php', 'p');
00028 if($this->shmkey == -1) {
00029 trigger_error("Unable to create SHM Key");
00030 return;
00031 }
00032
00033 $this->shmid = shm_attach($this->shmkey, $this->memsize, 0600);
00034 }
00035
00036 function set($key, $var, $expire=0)
00037 {
00038 $key = SITE_NAME."|$key";
00039
00040 $varkey = $this->_hash_key($key);
00041
00042 $dict = $this->_get_dict();
00043 if(@shm_put_var($this->shmid, $varkey, $var)) {
00044 $dict['keys'][$key] = array(
00045 'varkey' => $varkey,
00046 'expire' => $expire ? time()+$expire : 0
00047 );
00048 } else {
00049
00050 $this->delete($key);
00051 unset($dict['keys'][$key]);
00052
00053
00054 if(DEBUG === true) {
00055 echo "<p><b>Warning:</b> SHM Cache is out of space, consider enlarging it.</p>";
00056 }
00057 }
00058 $this->_set_dict($dict);
00059 }
00060
00061 function &get($key)
00062 {
00063 $key = SITE_NAME."|$key";
00064 $varkey = $this->_hash_key($key);
00065 $d = @shm_get_var($this->shmid, $varkey);
00066 return $d;
00067 }
00068
00069 function delete($key)
00070 {
00071 $key = SITE_NAME."|$key";
00072 $varkey = $this->_hash_key($key);
00073 return @shm_remove_var($this->shmid, $varkey);
00074 }
00075
00079 function flush()
00080 {
00081
00082 shm_remove($this->shmid);
00083 $this->shmid = shm_attach($this->shmkey, $this->memsize, 0600);
00084 }
00085
00089 function gc()
00090 {
00091 $dict = $this->_get_dict();
00092 foreach($dict['keys'] as $k=>$v) {
00093 if($v['expire'] && $v['expire'] <= time()) {
00094 shm_remove_var($this->shmid, $v['varkey']);
00095 unset($dict['keys'][$k]);
00096 }
00097 }
00098 $this->_set_dict($dict);
00099 }
00100
00104 function stats()
00105 {
00106
00107 $dict = $this->_get_dict();
00108 return array(
00109 'shmkey' => dechex($this->shmkey),
00110 'shmid' => $this->shmid,
00111 'dict' => $dict
00112 );
00113 }
00114
00118 function _get_dict()
00119 {
00120 $dict = @shm_get_var($this->shmid, 0);
00121 if(!$dict) $dict = array('nextvar'=>1, 'keys' => array());
00122 return $dict;
00123 }
00124
00125 function _set_dict($dict)
00126 {
00127 shm_put_var($this->shmid, 0, $dict);
00128 }
00129
00130 function _hash_key($key)
00131 {
00132 $dict = $this->_get_dict();
00133 if(isset($dict['keys'][$key])) {
00134 $varkey = $dict['keys'][$key]['varkey'];
00135 } else {
00136 $varkey = $dict['nextvar']++;
00137 $this->_set_dict($dict);
00138 }
00139 return $varkey;
00140 }
00141 }
00142
00143 ?>