CacheManager.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 call;
  18. class CacheManager
  19. {
  20. /**
  21. * @var ConfigInterface
  22. */
  23. protected $config;
  24. protected $drivers = [];
  25. /**
  26. * @var StdoutLoggerInterface
  27. */
  28. protected $logger;
  29. public function __construct(ConfigInterface $config, StdoutLoggerInterface $logger)
  30. {
  31. $this->config = $config;
  32. $this->logger = $logger;
  33. }
  34. public function getDriver($name = 'default'): DriverInterface
  35. {
  36. if (isset($this->drivers[$name]) && $this->drivers[$name] instanceof DriverInterface) {
  37. return $this->drivers[$name];
  38. }
  39. $config = $this->config->get("cache.{$name}");
  40. if (empty($config)) {
  41. throw new InvalidArgumentException(sprintf('The cache config %s is invalid.', $name));
  42. }
  43. $driverClass = $config['driver'] ?? RedisDriver::class;
  44. $driver = make($driverClass, ['config' => $config]);
  45. return $this->drivers[$name] = $driver;
  46. }
  47. public function call($callback, string $key, int $ttl = 3600, $config = 'default')
  48. {
  49. $driver = $this->getDriver($config);
  50. [$has, $result] = $driver->fetch($key);
  51. if ($has) {
  52. return $result;
  53. }
  54. $result = call($callback);
  55. $driver->set($key, $result, $ttl);
  56. return $result;
  57. }
  58. }