Repository navigation
Expand file tree
/
Copy pathCacheManager.php
More file actions
66 lines (51 loc) · 1.66 KB
/
Copy pathCacheManager.php
File metadata and controls
66 lines (51 loc) · 1.66 KB
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
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact [email protected]
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace Hyperf\Cache;
use Hyperf\Cache\Driver\DriverInterface;
use Hyperf\Cache\Driver\RedisDriver;
use Hyperf\Cache\Exception\InvalidArgumentException;
use Hyperf\Contract\ConfigInterface;
use Hyperf\Contract\StdoutLoggerInterface;
use function Hyperf\Support\make;
class CacheManager
{
/**
* @var DriverInterface[]
*/
protected array $drivers = [];
public function __construct(protected ConfigInterface $config, protected StdoutLoggerInterface $logger)
{
}
public function getDriver(string $name = 'default'): DriverInterface
{
if (isset($this->drivers[$name]) && $this->drivers[$name] instanceof DriverInterface) {
return $this->drivers[$name];
}
$config = $this->config->get("cache.{$name}");
if (empty($config)) {
throw new InvalidArgumentException(sprintf('The cache config %s is invalid.', $name));
}
$driverClass = $config['driver'] ?? RedisDriver::class;
$driver = make($driverClass, ['config' => $config]);
return $this->drivers[$name] = $driver;
}
public function call(callable $callback, string $key, int $ttl = 3600, $config = 'default')
{
$driver = $this->getDriver($config);
[$has, $result] = $driver->fetch($key);
if ($has) {
return $result;
}
$result = $callback();
$driver->set($key, $result, $ttl);
return $result;
}
}