php如何存到磁盘,php缓存----磁盘缓存

PHP开发也有几个月了,感觉php缓存是很重要的一块,无论是页面级的(主要指smarty)还是dao级的。使用上还不怎么熟,但还是记录下笔记。本篇讲述的缓存是写到磁盘文件,这是看piwik源码时看到的,感觉思想很好,这也得益于PHP的var_export 方法。主要把要保存的内容(int,string,也可以使array)保存为php文件,这样当include这个php文件后,保存的内容就自动当做变量被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;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值