-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathTogglSmartCache.php
More file actions
64 lines (54 loc) · 1.69 KB
/
Copy pathTogglSmartCache.php
File metadata and controls
64 lines (54 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?php
class TogglSmartCache{
private $ttl = 300;
private $name = '';
private $dir = '';
public function __construct($name, $ttl = 300, $dir = ''){
$this->ttl = $ttl;
if($dir == ''){
$dir = dirname(realpath(dirname(WEBROOT_DIR))) . '/tmp/cache';
}
$this->dir = $dir;
$this->name = $name;
}
public function getData(){
$data = $this->getDataFromCache();
if($data === false){
$data = $this->getDataFromSource();
if($data != null){
$this->cacheData($data);
}
} else {
unset($data['expiration']);
}
return $data;
}
public function getCacheFileName(){
return $this->dir . '/' . $this->name . '.cache';
}
public function expireCache(){
unlink($this->getCacheFileName());
}
public function getDataFromSource(){
throw new Exception("Must Override This Method");
}
public function getDataFromCache(){
$data = false;
if(file_exists($this->getCacheFileName())){
$serialized_data = file_get_contents($this->getCacheFileName());
$data = unserialize($serialized_data);
//If this is expired, return false
if($data['expiration'] < time()){
$data = false;
}
}
return $data;
}
public function cacheData($data){
$fh = fopen($this->dir . "/" . $this->name . '.cache', 'w+');
$expiration = time() + $this->ttl;
$data['expiration'] = $expiration;
fwrite($fh, serialize($data));
fclose($fh);
}
}