|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Koded\Caching; |
|
4
|
|
|
|
|
5
|
|
|
use Exception; |
|
6
|
|
|
use Psr\Cache\{CacheItemPoolInterface, InvalidArgumentException}; |
|
7
|
|
|
|
|
8
|
|
|
/** |
|
9
|
|
|
* CachePool creates instances of CacheItemPoolInterface classes. |
|
10
|
|
|
* The instances are created only once. |
|
11
|
|
|
* |
|
12
|
|
|
* Production ready: |
|
13
|
|
|
* |
|
14
|
|
|
* - Redis, with redis extension |
|
15
|
|
|
* - Redis, with Predis library |
|
16
|
|
|
* - Memcached |
|
17
|
|
|
* |
|
18
|
|
|
* Additional for development: |
|
19
|
|
|
* - File |
|
20
|
|
|
* - Memory |
|
21
|
|
|
* |
|
22
|
|
|
*/ |
|
23
|
|
|
final class CachePool |
|
24
|
|
|
{ |
|
25
|
|
|
/** @var CacheItemPoolInterface[] The registry */ |
|
26
|
|
|
private static array $instances = []; |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* @param string $client The name of the cache client |
|
30
|
|
|
* @param array $parameters [optional] Configuration parameters for the cache client |
|
31
|
|
|
* @return CacheItemPoolInterface |
|
32
|
|
|
*/ |
|
33
|
|
|
public static function use(string $client, array $parameters = []): CacheItemPoolInterface |
|
34
|
|
|
{ |
|
35
|
|
|
$ident = \md5($client . \serialize($parameters)); |
|
36
|
831 |
|
if (isset(self::$instances[$ident])) { |
|
37
|
|
|
return self::$instances[$ident]; |
|
38
|
831 |
|
} |
|
39
|
|
|
return self::$instances[$ident] = new class($client, $parameters) extends CacheItemPool |
|
40
|
831 |
|
{ |
|
41
|
822 |
|
public function __construct(string $client, array $parameters) |
|
42
|
|
|
{ |
|
43
|
|
|
$this->client = simple_cache_factory($client, $parameters); |
|
44
|
|
|
} |
|
45
|
|
|
}; |
|
46
|
9 |
|
} |
|
47
|
|
|
} |
|
48
|
9 |
|
|
|
49
|
9 |
|
/** |
|
50
|
|
|
* Implementation for \Psr\Cache\InvalidArgumentException |
|
51
|
|
|
* |
|
52
|
|
|
*/ |
|
53
|
|
|
class CachePoolException extends Exception implements InvalidArgumentException |
|
54
|
|
|
{ |
|
55
|
|
|
public static function from(Exception $e): static |
|
56
|
|
|
{ |
|
57
|
|
|
return new static($e->getMessage(), $e->getCode()); |
|
58
|
|
|
} |
|
59
|
|
|
} |
|
60
|
|
|
|