This repository was archived by the owner on Jul 20, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDBCache.php
More file actions
128 lines (106 loc) · 2.97 KB
/
DBCache.php
File metadata and controls
128 lines (106 loc) · 2.97 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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
<?php
namespace Cache;
use Cache\DBInstance;
class DBCache
{
/**
* Default database cache table name
*/
public $table = 'cache_system';
/**
* constructor
* @param object $conn PDO connection
* @param string $table database table
*/
public function __construct($conn, $table = null)
{
if ($table) {
$this->table = $table;
}
new DBInstance($conn);
}
public function generateKey ($id) {
$key = null;
if (is_string($id)) {
$key = $id;
} else {
$key = json_encode($id);
}
return $this->hash($key);
}
/**
* Hash a key using sha256
*/
public function hash ($key) {
return hash('sha256', $key);
}
/**
* Get the cache json as assoc
*/
public $assoc = false;
/**
* Get a cache result
* @param string $id
* @param int $max_life_time max life time in seconds
* @return mixed $res NULL if no result of if result is outdated. Else return the result
*/
public function get($id, $max_life_time = null)
{
$query = "SELECT * FROM {$this->table} WHERE id = ? ";
$db = DBInstance::get();
$row = $db->prepareFetch($query, [$this->generateKey($id)]);
if (empty($row)) {
return null;
}
if ($max_life_time) {
$expire = $row['unix_ts'] + $max_life_time;
if ($expire < time()) {
$this->delete($this->generateKey($id));
return null;
} else {
return json_decode($row['data'], $this->assoc);
}
} else {
return json_decode($row['data'], $this->assoc);
}
}
/**
* Sets a string in cache
* @param int $id
* @param string $data
* @return string $res true on succes else false
*/
public function set($id, $data)
{
$db = DBInstance::get();
$db->beginTransaction();
$res = $this->delete($id);
if (!$res) {
$db->rollback();
return false;
}
$query = "INSERT INTO {$this->table} (id, unix_ts, data) VALUES (?, ?, ?)";
$res = $db->prepareExecute($query, [$this->generateKey($id), time(), json_encode($data) ]);
if (!$res) {
$db->rollback();
return false;
}
return $db->commit();
}
/**
* Delete a string from cache
* @param int $id
* @return boolean $res db result
*/
public function delete($id)
{
$db = DBInstance::get();
$query = "SELECT * FROM {$this->table} WHERE id = ?";
$row = $db->prepareFetch($query, [$this->generateKey($id)]);
if (!empty($row)) {
$query = "DELETE FROM {$this->table} WHERE id = ?";
return $db->prepareExecute($query, [$this->generateKey($id)]);
}
return true;
}
}