-
Notifications
You must be signed in to change notification settings - Fork 0
/
CacheTrait.php
129 lines (115 loc) · 2.67 KB
/
CacheTrait.php
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
129
<?php
/**
* Cache Trait
*
* @package Molajo
* @copyright 2014-2015 Amy Stephen. All rights reserved.
* @license http://www.opensource.org/licenses/mit-license.html MIT License
*/
namespace CommonApi\Cache;
/**
* Cache Trait
*
* @package Cache
* @copyright 2014-2015 Amy Stephen. All rights reserved.
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @since 1.0.0
*/
trait CacheTrait
{
/**
* Function to Get Cache
*
* @var callable
* @since 1.0
*/
protected $get_cache_callback;
/**
* Function to Set Cache
*
* @var callable
* @since 1.0
*/
protected $set_cache_callback;
/**
* Function to Delete Cache, either by key or all
*
* @var callable
* @since 1.0
*/
protected $delete_cache_callback;
/**
* Cache Type
*
* @var string
* @since 1.0
*/
protected $cache_type;
/**
* Retrieve cache value
*
* @param string $key
*
* @return object CommonApi\Cache\CacheItemInterface
* @since 1.0.0
*/
public function getCache($key)
{
$cache_function = $this->get_cache_callback;
return $cache_function($this->cache_type, array('key' => $key));
}
/**
* Persist data in cache
*
* @param string $key
* @param mixed $value
* @param integer $ttl (number of seconds)
*
* @return bool
* @since 1.0.0
*/
public function setCache($key, $value, $ttl = 0)
{
$cache_function = $this->set_cache_callback;
return $cache_function($this->cache_type, array('key' => $key, 'value' => $value, 'ttl' => $ttl));
}
/**
* Delete cache for specified $key value or expired cache
*
* @param string $key
*
* @return bool
* @since 1.0.0
*/
public function deleteCache($key)
{
$cache_function = $this->delete_cache_callback;
return $cache_function($this->cache_type, array('key' => $key));
}
/**
* Clear all cache
*
* @return bool
* @since 1.0.0
*/
public function clearCache()
{
$cache_function = $this->delete_cache_callback;
return $cache_function($this->cache_type, array());
}
/**
* Determine if Cache is activated for this type
*
* @return boolean
* @since 1.0
*/
public function useCache()
{
if (is_callable($this->get_cache_callback)
&& is_callable($this->set_cache_callback)
&& is_callable($this->delete_cache_callback)) {
return true;
}
return false;
}
}