CacheManager.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Cache;
  12. use Hyperf\Cache\Driver\DriverInterface;
  13. use Hyperf\Cache\Driver\RedisDriver;
  14. use Hyperf\Cache\Exception\InvalidArgumentException;
  15. use Hyperf\Contract\ConfigInterface;
  16. use Hyperf\Contract\StdoutLoggerInterface;
  17. use function Hyperf\Support\make;
  18. class CacheManager
  19. {
  20. /**
  21. * @var DriverInterface[]
  22. */
  23. protected array $drivers = [];
  24. public function __construct(protected ConfigInterface $config, protected StdoutLoggerInterface $logger)
  25. {
  26. }
  27. public function getDriver(string $name = 'default'): DriverInterface
  28. {
  29. if (isset($this->drivers[$name]) && $this->drivers[$name] instanceof DriverInterface) {
  30. return $this->drivers[$name];
  31. }
  32. $config = $this->config->get("cache.{$name}");
  33. if (empty($config)) {
  34. throw new InvalidArgumentException(sprintf('The cache config %s is invalid.', $name));
  35. }
  36. $driverClass = $config['driver'] ?? RedisDriver::class;
  37. $driver = make($driverClass, ['config' => $config]);
  38. return $this->drivers[$name] = $driver;
  39. }
  40. public function call(callable $callback, string $key, int $ttl = 3600, $config = 'default')
  41. {
  42. $driver = $this->getDriver($config);
  43. [$has, $result] = $driver->fetch($key);
  44. if ($has) {
  45. return $result;
  46. }
  47. $result = $callback();
  48. $driver->set($key, $result, $ttl);
  49. return $result;
  50. }
  51. }