-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileCache.php
More file actions
107 lines (90 loc) · 2.47 KB
/
Copy pathFileCache.php
File metadata and controls
107 lines (90 loc) · 2.47 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<?php
/*
Manage as one cache file per person
*/
class FileCache
{
// 파일저장 경로
const PATH = '/home/cache';
// 파일저장 확장자
const EXTENSION = '.cache';
// person id
private $id = '';
private $filePath = '';
public function __construct($id)
{
if ($id) {
$this->init($id);
} else {
echo 'cache not found id!';
}
}
private function init($id)
{
$this->id = trim($id);
$this->initFilePath();
}
public function get($cacheName)
{
$cacheName = trim($cacheName);
$cache = $this->getCache();
if (
$cache === null ||
!is_array($cache) ||
!array_key_exists($cacheName, $cache)
) {
$cacheData = false;
} else {
$cacheData = $cache[$cacheName];
// 기간 만료됬으면 데이터 삭제함
if ($this->isExpired($cacheData)) {
unset($cache[$cacheName]);
$this->setCache($cache);
$cacheData = false;
} else {
$cacheData = unserialize($cacheData['data']);
}
}
return $cacheData;
}
// time : 1 = 1 sec
public function set($cacheName, $value, $time = 60)
{
$cacheName = trim($cacheName);
$cacheData = [
'setTime' => time(),
'cacheTime' => (int) $time,
'data' => serialize($value),
];
$cache = $this->getCache();
if (!$cache) {
$cache = [];
}
$cache[$cacheName] = $cacheData;
$this->setCache($cache);
}
private function getCache()
{
if (file_exists($this->filePath)) {
$data = file_get_contents($this->filePath);
$cache = json_decode($data, true);
} else {
$cache = null;
}
return $cache;
}
private function setCache($cache)
{
file_put_contents($this->filePath, json_encode($cache));
}
private function isExpired($cacheData)
{
$expiresOn = $cacheData['setTime'] + $cacheData['cacheTime'];
return $expiresOn < time();
}
private function initFilePath()
{
$filePrefix = 'fileCache_';
$this->filePath = self::PATH . '/' . $filePrefix . $this->id . self::EXTENSION;
}
}