-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCache.php
92 lines (77 loc) · 2.25 KB
/
Cache.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
<?php
/**
* This file is part of the RobiNN\Cache.
* Copyright (c) Róbert Kelčák (https://kelcak.com/)
*/
declare(strict_types=1);
namespace RobiNN\Cache;
class Cache {
final public const VERSION = '2.6.4';
private readonly CacheInterface $cache;
/**
* @param array<string, mixed> $config
* @param array<string, string> $custom_storages
*
* @throws CacheException
*/
public function __construct(array $config = [], array $custom_storages = []) {
$storages = [
'apcu' => Storages\APCuStorage::class,
'file' => Storages\FileStorage::class,
'memcached' => Storages\MemcachedStorage::class,
'redis' => Storages\RedisStorage::class,
...$custom_storages,
];
$storage = isset($storages[$config['storage']]) ? $config['storage'] : 'file';
$server_info = $config[$storage] ?? [];
$this->cache = is_subclass_of($storages[$storage], CacheInterface::class) ?
new ($storages[$storage])($server_info) :
new Storages\FileStorage($server_info);
}
/**
* Check connection.
*/
public function isConnected(): bool {
return $this->cache->isConnected();
}
/**
* Check if the data is cached.
*/
public function exists(string $key): bool {
return $this->cache->exists($key);
}
/**
* Save data to cache.
*/
public function set(string $key, mixed $data, int $seconds = 0): bool {
return $this->cache->set($key, $data, $seconds);
}
/**
* Get data by key.
*/
public function get(string $key): mixed {
return $this->cache->get($key);
}
/**
* Get the data or store if it is not cached.
*/
public function remember(string $key, mixed $data, int $seconds = 0): mixed {
if ($this->exists($key)) {
return $this->get($key);
}
$this->set($key, $data, $seconds);
return $data;
}
/**
* Delete data by key.
*/
public function delete(string $key): bool {
return $this->cache->delete($key);
}
/**
* Delete all data from cache.
*/
public function flush(): bool {
return $this->cache->flush();
}
}