因爲我使用共享託管軟件包,並且即時通訊無法使用PECL Memcache,所以我希望在使用我自己的小緩存系統或使用PEAR Cache_Lite系統之間對自己的疑問提供一些技巧。
因此,這裏是我的功能:
<?php
//this one create a simple .txt file named by unique query_key string generated width e.g $file_name=md5("SELECT * FROM table"); content of that file is serialized value of mysql return
function write($query_key,$result)
{
global $config;
$new_file_name=md5($query_key);
$result_to_write=serialize($result);
if($handle=opendir($config['cache_dir']))
{
$f=fopen($config['cache_dir'].$new_file_name.'.txt','w+');
fwrite($f,$result_to_write);
fclose($f);
closedir($handle);
}
}
// this one reads content of file (serialized mysql return of unique query_key) if timeout hes not expired, and if it is it return false
function read($query_key,$timeout)
{
global $config;
$file_name=md5($query_key);
if($handle=opendir($config['cache_dir']))
{
if(file_exists($config['cache_dir'].$file_name.'.txt'))
{
$last_accessed=filemtime($config['cache_dir'].$file_name.'.txt');
$now=time();
if(($now-$last_accessed)<$timeout)
{
$file=fopen($config['cache_dir'].$file_name.'.txt','rb');
$f=fread($file,filesize($config['cache_dir'].$file_name.'.txt'));
$array=unserialize($f);
fclose($file);
closedir($handle);
}else{ return FALSE; }
}else{ return FALSE; }
}
if(!empty($array)) return $array;
else return FALSE;
}
//and finally this one which is used when executing query, so it has timeout in seconds, if file (cached result) exists, and timeout has not expired, it returnt cached data , or it reads from database returns new result,and cache new result by writing new file
function cache($query)
{
$timeout=600;
$file_exists=read($query,$timeout);
if($file_exists)
{
return $file_exists;
}else{
$result=get_rows($query);
write($query,$result);
return $result;
}
}
?>
這是我的小「系統緩存」的作品非常好,因爲我可以看到,PEAR Cache_Lite作品幾乎同樣的方式,和我不熟悉梨緩存系統,我想知道什麼是更好,更安全和更快的解決方案之間使用這兩個,爲什麼?
謝謝!
的開始,經編所有你在一個類碼,然後allso可以保持「文件句柄」打開,直到應用程序完成請求,這不是很好的解決方案,打開和關閉文件很多次。 – 2011-03-01 13:35:51
是否安裝了Memcache? – powtac 2011-03-01 13:36:35
這可能屬於[CodeReview.StackExchange](http://codereview.stackexchange.com/)... – ircmaxell 2011-03-01 13:42:36