-
Notifications
You must be signed in to change notification settings - Fork 1
/
CachePool.php
59 lines (54 loc) · 1.53 KB
/
CachePool.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
<?php
namespace Koded\Caching;
use Exception;
use Psr\Cache\{CacheItemPoolInterface, InvalidArgumentException};
/**
* CachePool creates instances of CacheItemPoolInterface classes.
* The instances are created only once.
*
* Production ready:
*
* - Redis, with redis extension
* - Redis, with Predis library
* - Memcached
*
* Additional for development:
* - File
* - Memory
*
*/
final class CachePool
{
/** @var CacheItemPoolInterface[] The registry */
private static array $instances = [];
/**
* @param string $client The name of the cache client
* @param array $parameters [optional] Configuration parameters for the cache client
* @return CacheItemPoolInterface
*/
public static function use(string $client, array $parameters = []): CacheItemPoolInterface
{
$ident = \md5($client . \serialize($parameters));
if (isset(self::$instances[$ident])) {
return self::$instances[$ident];
}
return self::$instances[$ident] = new class($client, $parameters) extends CacheItemPool
{
public function __construct(string $client, array $parameters)
{
$this->client = simple_cache_factory($client, $parameters);
}
};
}
}
/**
* Implementation for \Psr\Cache\InvalidArgumentException
*
*/
class CachePoolException extends Exception implements InvalidArgumentException
{
public static function from(Exception $e): static
{
return new static($e->getMessage(), $e->getCode());
}
}