php中使用文件缓存的例子
发布时间:2020-05-25 07:07:00 所属栏目:PHP 来源:互联网
导读:php中使用文件缓存的例子
|
下面是脚本之家 jb51.cc 通过网络收集整理的代码片段。 脚本之家小编现在分享给大家,也给大家做个参考。 <?php
class CacheLayer{
protected $root = "";
protected $cache = "";
protected $key = "";
protected $life = 0;
public function __construct($key,$root = "/cachelayer"){
$this->root = $_SERVER["DOCUMENT_ROOT"].$root;
$this->key = $key;
}
public function expired($life_span){
$this->life = $life_span;
$file = $this->root."/".$this->key.".cachelayer";
if(is_file($file)){
$mtime = filemtime($file);
return (time() >= ($mtime + $this->life));
}else{
return true;
}
}
public function put($content){
$file = $this->root."/".$this->key.".cachelayer";
if(!is_dir(dirname($this->root))){
return false;
}
$this->delete();
$content = json_encode($content);
return (bool)file_put_contents($file,$content);
}
public function get(){
$file = $this->root."/".$this->key.".cachelayer";
if(is_file($file)){
return json_decode(file_get_contents($file),true);
}
return array();
}
public function delete(){
$file = $this->root."/".$this->key.".cachelayer";
if(is_file($file)){
unlink($file);
return true;
}
return false;
}
}
<?php
// Load the cachelayer and the database connection (db connection is optional)
require_once "CacheLayer.php";
require_once "db_connection.php";
// Create a instance of the cachelayer
$cl_nav = new CacheLayer("navigation");
// Check to see if the cache is expired (60 * 10 = 10 minutes)
if($cl_nav->expired(60 * 10)){
echo "Cache doesn't exist or is expired. Rebuilding...<br />";
// if the cache is expired rebuild it
$result = mysql_query("select id,title from navigation");
$new_cache = array();
while($row = mysql_fetch_assoc($result)){
$new_cache[] = $row;
}
// Save the array into the cache
$cl_nav->put($new_cache);
}
echo "Loading from cache...<br />";
// Get the cache
$cache = $cl_nav->get();
// Display the cache
foreach($cache as $row){
$id = $row["id"];
$title = $row["title"];
echo "<a href='/$id/$title'>$title</a><br />";
}
以上是脚本之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。 如果觉得脚本之家网站内容还不错,欢迎将脚本之家网站推荐给程序员好友。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
