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