1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Ds\Cache; |
4
|
|
|
|
5
|
|
|
use Ds\Cache\Interfaces\CacheInterface; |
6
|
|
|
use Ds\Cache\Interfaces\CacheStorageInterface; |
7
|
|
|
|
8
|
|
|
class Cache implements CacheInterface |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* @var CacheStorageInterface |
12
|
|
|
*/ |
13
|
|
|
protected $cache; |
14
|
|
|
|
15
|
|
|
protected $expires; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Cache constructor. |
19
|
|
|
* @param CacheStorageInterface|null $cacheStorage |
20
|
|
|
* @param int $expireDefault |
21
|
|
|
*/ |
22
|
|
|
public function __construct(CacheStorageInterface $cacheStorage = null, $expireDefault = 60) |
23
|
|
|
{ |
24
|
|
|
$this->cache = $cacheStorage; |
25
|
|
|
$this->expires = $expireDefault; |
26
|
|
|
|
27
|
|
|
if ($cacheStorage === null) { |
28
|
|
|
$this->cache = new NullStorage(); |
29
|
|
|
} |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* Check if cache key exists. |
34
|
|
|
* @param $key |
35
|
|
|
* @return bool |
36
|
|
|
*/ |
37
|
|
|
public function has($key) |
38
|
|
|
{ |
39
|
|
|
return $this->cache->has($key); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Save Cache Value. |
44
|
|
|
* @param string $key |
45
|
|
|
* @param mixed $value |
46
|
|
|
* @param int $expires |
47
|
|
|
* @return void |
48
|
|
|
*/ |
49
|
|
|
public function set($key, $value, $expires = null) |
50
|
|
|
{ |
51
|
|
|
if ($expires === null){ |
52
|
|
|
$expires = $this->expires; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
return $this->cache->set($key, $value, $expires); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @param int $expires |
60
|
|
|
* @return Cache |
61
|
|
|
*/ |
62
|
|
|
public function setExpires($expires){ |
63
|
|
|
$this->expires = $expires; |
64
|
|
|
return $this; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* Get Cache Value from key. |
69
|
|
|
* @param string $key |
70
|
|
|
* @return mixed |
71
|
|
|
*/ |
72
|
|
|
public function get($key = '') |
73
|
|
|
{ |
74
|
|
|
return $this->cache->get($key); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* Delete Cache Key. |
79
|
|
|
* @param $key |
80
|
|
|
*/ |
81
|
|
|
public function delete($key) |
82
|
|
|
{ |
83
|
|
|
$this->cache->delete($key); |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
/** |
87
|
|
|
* Create new instance with $CacheStorage |
88
|
|
|
* @param CacheStorageInterface $cacheStorage |
89
|
|
|
* @return CacheInterface |
90
|
|
|
*/ |
91
|
|
|
public function withCacheStorage(CacheStorageInterface $cacheStorage) |
92
|
|
|
{ |
93
|
|
|
$new = clone $this; |
94
|
|
|
$new->cache = $cacheStorage; |
95
|
|
|
return $new; |
96
|
|
|
} |
97
|
|
|
|
98
|
|
|
/** |
99
|
|
|
* Get Cache Storage |
100
|
|
|
* @return CacheStorageInterface |
101
|
|
|
*/ |
102
|
|
|
public function getCacheStorage() |
103
|
|
|
{ |
104
|
|
|
return $this->cache; |
105
|
|
|
} |
106
|
|
|
} |
107
|
|
|
|