Skip to content

Commit ed74a20

Browse files
committed
main class
1 parent 520ed18 commit ed74a20

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

SQLite3DataCache.php

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
<?php
2+
3+
class SQLite3DataCache
4+
{
5+
private $sqlite3_db; //SQLite3 db
6+
7+
public function __construct() {
8+
$target_directory = __DIR__.'/../../cache_files';
9+
$file_name = 'cache.sqlite3db';
10+
if (!file_exists($target_directory) && !mkdir($target_directory, 0777, true)) {
11+
die('Failed to create folder/file');
12+
}
13+
$this->sqlite3_db = new SQLite3($target_directory.'/'.$file_name,SQLITE3_OPEN_CREATE|SQLITE3_OPEN_READWRITE);
14+
$stmt = @$this->sqlite3_db->prepare("SELECT * FROM cache");
15+
if($stmt===false) {
16+
$this->sqlite3_db->exec("CREATE TABLE cache
17+
(server_name VARCHAR(35),
18+
key VARCHAR(40),
19+
value VARCHAR(100),
20+
valid_upto_unixtime INTEGER)");
21+
}
22+
}
23+
24+
public function get($key) {
25+
$cur_unixtime = time();
26+
$output = [];
27+
$output['value'] = false;
28+
$output['available'] = false;
29+
$key = $this->sqlite3_db->escapeString($key);
30+
// fetch only first column, only single row
31+
$result = $this->sqlite3_db->querySingle("
32+
SELECT value from cache where key='$key' and
33+
(valid_upto_unixtime=0 or valid_upto_unixtime>=$cur_unixtime)");
34+
if($result===false) {
35+
$output['message'] = 'cache query error';
36+
return $output;
37+
}
38+
if($result===null) { // empty array is returned if all columns fetched
39+
return $output;
40+
}
41+
$output['available'] = true;
42+
$output['value'] = $result;
43+
return $output;
44+
}
45+
46+
public function set($key,$value,$valid_upto = 0) {
47+
$key = $this->sqlite3_db->escapeString($key);
48+
$value = $this->sqlite3_db->escapeString($value);
49+
50+
$result = $this->sqlite3_db->exec("
51+
DELETE FROM cache WHERE server_name = '{$_SERVER['SERVER_NAME']}'
52+
and key='$key'");
53+
54+
if($result===false)
55+
return false;
56+
57+
$result = $this->sqlite3_db->exec("
58+
INSERT INTO cache VALUES ('{$_SERVER['SERVER_NAME']}',
59+
'$key','$value',$valid_upto )");
60+
return $result;
61+
}
62+
63+
public function delete($key) {
64+
$key = $this->sqlite3_db->escapeString($key);
65+
$value = $this->sqlite3_db->escapeString($value);
66+
$result = $this->sqlite3_db->exec("
67+
DELETE FROM cache WHERE key = '$key' ");
68+
return $result;
69+
}
70+
71+
public function __destruct() {
72+
$this->sqlite3_db->close();
73+
}
74+
75+
}
76+

0 commit comments

Comments
 (0)