1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Vectorface\Cache; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Class with a few methods that may assist in implementing item caching. |
7
|
|
|
*/ |
8
|
|
|
class CacheHelper |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* Implement the mechanics of caching the result of a heavy function call. |
12
|
|
|
* |
13
|
|
|
* For example, if one has a function like so: |
14
|
|
|
* public static function getLargeDatasetFromDB($arg1, $arg2) { |
15
|
|
|
* // Lots of SQL/compute |
16
|
|
|
* return $giantDataSet; |
17
|
|
|
* } |
18
|
|
|
* |
19
|
|
|
* One could cache this by adding cache calls to the top/bottom. CacheHelper::fetch can automatate this: |
20
|
|
|
* |
21
|
|
|
* function getLargeDataset($arg1, $arg2) { |
22
|
|
|
* $key = "SomeClass::LargeDataset($arg1,$arg2)"; |
23
|
|
|
* $cache = new APCCache(); |
24
|
|
|
* return CacheHelper::fetch($cache, $key, [SomeClass, 'getLargeDatasetFromDB'], [$arg1, $arg2], 600); |
25
|
|
|
* } |
26
|
|
|
* |
27
|
|
|
* @param Cache $cache The cache from/to which the values should be retrieved/set. |
28
|
|
|
* @param string $key The cache key which should store the value. |
29
|
|
|
* @param callable $callback A callable which is expected to return a value to be cached. |
30
|
|
|
* @param mixed[] $args The arguments to be passed to the callback, if it needs to be called. |
31
|
|
|
* @param int $ttl If a value is to be set in the cache, set this expiry time (in seconds). |
32
|
|
|
* @return mixed The value stored in the cache, or returned by the callback. |
33
|
|
|
*/ |
34
|
1 |
|
public static function fetch(Cache $cache, string $key, callable $callback, array $args = [], $ttl = 300) |
35
|
|
|
{ |
36
|
1 |
|
$item = $cache->get($key); |
37
|
1 |
|
if ($item === null) { |
38
|
1 |
|
$item = $callback(...$args); |
39
|
|
|
|
40
|
1 |
|
if (isset($item)) { |
41
|
1 |
|
$cache->set($key, $item, $ttl); |
42
|
|
|
} |
43
|
|
|
} |
44
|
1 |
|
return $item; |
45
|
|
|
} |
46
|
|
|
} |
47
|
|
|
|