1 | <?php |
||
14 | abstract class AbstractCachingService { |
||
15 | |||
16 | /** |
||
17 | * The key used to cache the data. |
||
18 | * |
||
19 | * @var string |
||
20 | */ |
||
21 | protected $cacheKey; |
||
22 | |||
23 | /** |
||
24 | * The key used to cache the timestamp of the last |
||
25 | * refreshCache() call. |
||
26 | * |
||
27 | * @var string |
||
28 | */ |
||
29 | protected $cacheTimestampKey; |
||
30 | |||
31 | |||
32 | /** |
||
33 | * @param string $cacheKey |
||
34 | * @param string $cacheTimestampKey |
||
35 | */ |
||
36 | 12 | public function __construct($cacheKey, $cacheTimestampKey) |
|
37 | { |
||
38 | 12 | $this->cacheKey = $cacheKey; |
|
39 | 12 | $this->cacheTimestampKey = $cacheTimestampKey; |
|
40 | 12 | } |
|
41 | |||
42 | /** |
||
43 | * Returns the timestamp of the last refreshCache() call. |
||
44 | * |
||
45 | * @return DateTime |
||
46 | */ |
||
47 | 4 | public function getLastRefreshTimestamp() |
|
48 | { |
||
49 | 4 | $unixTime = Cache::get($this->cacheTimestampKey); |
|
50 | |||
51 | 4 | $dateTime = new DateTime; |
|
52 | 4 | $dateTime->setTimestamp($unixTime); |
|
53 | |||
54 | 4 | return $dateTime; |
|
55 | } |
||
56 | |||
57 | /** |
||
58 | * Refresh the cached data. |
||
59 | * |
||
60 | * @param mixed $data |
||
61 | */ |
||
62 | 8 | public function refreshCacheUsing($data) |
|
63 | { |
||
64 | 8 | Cache::forever($this->cacheKey, $data); |
|
65 | 8 | Cache::forever($this->cacheTimestampKey, time()); |
|
66 | 8 | } |
|
67 | |||
68 | /** |
||
69 | * Create up-to-date data and update cache using refreshCacheUsing(). |
||
70 | * Trigger some event. |
||
71 | * |
||
72 | * @return void |
||
73 | */ |
||
74 | abstract public function refreshCache(); |
||
75 | |||
76 | /** |
||
77 | * Return the cached data. Refresh cache if cache has not yet been initialized. |
||
78 | * |
||
79 | * @return mixed |
||
80 | */ |
||
81 | 5 | public function getData() |
|
89 | |||
90 | } |