php如何存到磁盘,php缓存----磁盘缓存
PHP開發(fā)也有幾個月了,感覺php緩存是很重要的一塊,無論是頁面級的(主要指smarty)還是dao級的。使用上還不怎么熟,但還是記錄下筆記。本篇講述的緩存是寫到磁盤文件,這是看piwik源碼時看到的,感覺思想很好,這也得益于PHP的var_export 方法。主要把要保存的內(nèi)容(int,string,也可以使array)保存為php文件,這樣當include這個php文件后,保存的內(nèi)容就自動當做變量被include進來了。
源碼如下:
class Piwik_CacheFile
{
protected $cachePath;
protected $cachePrefix;
function __construct($directory)
{
$this->cachePath = PIWIK_USER_PATH . '/tmp/cache/' . $directory . '/';
}
function get($id)
{
$cache_complete = false;
$content = '';
// We are assuming that most of the time cache will exists
$ok = @include($this->cachePath . $id . '.php');
if ($ok && $cache_complete == true) {
return $content;
}
return false;
}
function set($id, $content)
{
if( !is_dir($this->cachePath))
{
Piwik_Common::mkdir($this->cachePath);
}
if (!is_writable($this->cachePath)) {
return false;
}
$id = $this->cachePath . $id . '.php';
$cache_literal = "
$cache_literal .= "$"."content = ".var_export($content, true).";\n\n";
$cache_literal .= "$"."cache_complete = true;\n\n";
$cache_literal .= "?".">";
// Write cache to a temp file, then rename it, overwritng the old cache
// On *nix systems this should guarantee atomicity
$tmp_filename = tempnam($this->cachePath, 'tmp_');
if ($fp = @fopen($tmp_filename, 'wb')) {
@fwrite ($fp, $cache_literal, strlen($cache_literal));
@fclose ($fp);
if (!@rename($tmp_filename, $id)) {
// On some systems rename() doesn't overwrite destination
@unlink($id);
if (!@rename($tmp_filename, $id)) {
// Make sure that no temporary file is left over
// if the destination is not writable
@unlink($tmp_filename);
}
}
return true;
}
return false;
}
function delete($id)
{
$filename = $this->cachePath . $id . '.php';
if (file_exists($filename)) {
@unlink ($filename);
return true;
}
return false;
}
}
總結(jié)
以上是生活随笔為你收集整理的php如何存到磁盘,php缓存----磁盘缓存的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php 直接定义 和 construct
- 下一篇: linux 文件夹换所属用户,Linux