1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace ByJG\Cache\Psr16; |
4
|
|
|
|
5
|
|
|
class SessionCacheEngine extends BaseCacheEngine |
6
|
|
|
{ |
7
|
|
|
|
8
|
|
|
protected $prefix = null; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* SessionCacheEngine constructor. |
12
|
|
|
* |
13
|
|
|
* @param string $prefix |
14
|
|
|
*/ |
15
|
|
|
public function __construct($prefix = 'cache') |
16
|
|
|
{ |
17
|
|
|
$this->prefix = $prefix; |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
|
21
|
|
|
protected function checkSession() |
22
|
|
|
{ |
23
|
|
|
if (session_status() == PHP_SESSION_NONE) { |
24
|
|
|
session_start(); |
25
|
|
|
} |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
protected function keyName($key) |
29
|
|
|
{ |
30
|
|
|
return $this->prefix . '-' . $key; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public function get($key, $default = null) |
|
|
|
|
34
|
|
|
{ |
35
|
|
|
$this->checkSession(); |
36
|
|
|
|
37
|
|
|
$keyName = $this->keyName($key); |
38
|
|
|
|
39
|
|
|
if ($this->has($key)) { |
40
|
|
|
return $_SESSION[$keyName]; |
41
|
|
|
} else { |
42
|
|
|
return $default; |
43
|
|
|
} |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
public function delete($key) |
|
|
|
|
47
|
|
|
{ |
48
|
|
|
$this->checkSession(); |
49
|
|
|
|
50
|
|
|
$keyName = $this->keyName($key); |
51
|
|
|
|
52
|
|
|
if (isset($_SESSION[$keyName])) { |
53
|
|
|
unset($_SESSION[$keyName]); |
54
|
|
|
} |
55
|
|
|
if (isset($_SESSION["$keyName.ttl"])) { |
56
|
|
|
unset($_SESSION["$keyName.ttl"]); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
public function set($key, $value, $ttl = null) |
|
|
|
|
61
|
|
|
{ |
62
|
|
|
$this->checkSession(); |
63
|
|
|
|
64
|
|
|
$keyName = $this->keyName($key); |
65
|
|
|
$_SESSION[$keyName] = $value; |
66
|
|
|
if (!empty($ttl)) { |
67
|
|
|
$_SESSION["$keyName.ttl"] = $this->addToNow($ttl); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
public function clear() |
72
|
|
|
{ |
73
|
|
|
session_destroy(); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
public function has($key) |
|
|
|
|
77
|
|
|
{ |
78
|
|
|
$keyName = $this->keyName($key); |
79
|
|
|
|
80
|
|
|
if (isset($_SESSION[$keyName])) { |
81
|
|
|
if (isset($_SESSION["$keyName.ttl"]) && time() >= $_SESSION["$keyName.ttl"]) { |
82
|
|
|
$this->delete($key); |
83
|
|
|
return false; |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
return true; |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
return false; |
90
|
|
|
} |
91
|
|
|
|
92
|
|
|
public function isAvailable() |
93
|
|
|
{ |
94
|
|
|
try { |
95
|
|
|
$this->checkSession(); |
96
|
|
|
return true; |
97
|
|
|
} catch (\Exception $ex) { |
98
|
|
|
return false; |
99
|
|
|
} |
100
|
|
|
} |
101
|
|
|
} |
102
|
|
|
|
Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable: