1 | <?php |
||
18 | class SimpleCache |
||
19 | { |
||
20 | |||
21 | /** |
||
22 | * @param $key |
||
23 | * @param $data |
||
24 | * @return bool |
||
25 | * |
||
26 | * Add object to cache list and save object as json file |
||
27 | */ |
||
28 | public static function add($key, $data, $ttl = 0) |
||
29 | { |
||
30 | $tempFilePath = static::getTempFile($key) ?: static::createTempFile($key, $ttl); |
||
31 | return (bool)file_put_contents($tempFilePath, static::encode($data)); |
||
32 | } |
||
33 | |||
34 | /** |
||
35 | * @param $key |
||
36 | * @param string $className |
||
37 | * @return object|bool |
||
38 | * |
||
39 | * Fetch object from cache |
||
40 | */ |
||
41 | public static function fetch($key, $className) |
||
42 | { |
||
43 | if (CacheManager::has($key)) { |
||
44 | $dataString = file_get_contents(static::getTempFile($key)); |
||
45 | |||
46 | $mapper = new JsonMapper(); |
||
47 | return $mapper->map(static::decode($dataString), (new ReflectionClass($className))->newInstanceWithoutConstructor()); |
||
48 | } |
||
49 | |||
50 | return false; |
||
51 | } |
||
52 | |||
53 | /** |
||
54 | * @param $key |
||
55 | * @return bool |
||
56 | * |
||
57 | * Remove object from cache |
||
58 | */ |
||
59 | public static function remove($key) |
||
60 | { |
||
61 | if (CacheManager::has($key)) { |
||
62 | unlink(CacheManager::get($key)); |
||
63 | return CacheManager::remove($key); |
||
64 | } |
||
65 | |||
66 | return false; |
||
67 | } |
||
68 | |||
69 | /** |
||
70 | * @param $key |
||
71 | * @return bool |
||
72 | * |
||
73 | * Check object is cached or not |
||
74 | */ |
||
75 | public static function exists($key) |
||
76 | { |
||
77 | return file_exists(static::getTempFile($key)); |
||
78 | } |
||
79 | |||
80 | /** |
||
81 | * @param $key |
||
82 | * @return bool|string |
||
83 | */ |
||
84 | public static function getTempFile($key) |
||
92 | |||
93 | /** |
||
94 | * @param $key |
||
95 | * @return bool|string |
||
96 | */ |
||
97 | public static function createTempFile($key, $ttl) |
||
104 | |||
105 | /** |
||
106 | * @param object $object |
||
107 | * @return string |
||
108 | */ |
||
109 | protected static function encode($object) |
||
113 | |||
114 | /** |
||
115 | * @param string $string |
||
116 | * @return object |
||
117 | */ |
||
118 | protected static function decode($string) |
||
122 | } |