Cache.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace Easemob\Cache;
  3. /**
  4. * @ignore 文件缓存类
  5. * @final
  6. */
  7. final class Cache
  8. {
  9. /**
  10. * 获取缓存 key
  11. * @param string $name 缓存名称
  12. * @return string 缓存 key
  13. */
  14. public static function getCacheKey($name)
  15. {
  16. return md5($name) . '.php';
  17. }
  18. /**
  19. * 获取缓存值
  20. * @param string $name 缓存名称
  21. * @return mixed 缓存值
  22. */
  23. public static function get($name)
  24. {
  25. $path = __DIR__ . '/../../runtime/cache';
  26. $filename = $path . '/' . self::getCacheKey($name);
  27. if (!file_exists($filename)) {
  28. return null;
  29. }
  30. $content = file_get_contents($filename);
  31. $data = json_decode($content, true);
  32. return $data['expire'] <= time() ? null : $data['value'];
  33. }
  34. /**
  35. * 设置缓存值
  36. * @param string $name 缓存名称
  37. * @param mixed $value 缓存值
  38. * @param int $expire 过期时间
  39. * @return boolean 是否设置成功
  40. */
  41. public static function set($name, $value, $expire = 3600)
  42. {
  43. $path = __DIR__ . '/../../runtime/cache';
  44. if (!is_dir($path)) {
  45. mkdir($path, 0755, true);
  46. }
  47. $filename = self::getCacheKey($name);
  48. $data = array(
  49. 'value' => $value,
  50. 'expire' => time() + $expire,
  51. );
  52. $result = file_put_contents($path . '/' . $filename, json_encode($data));
  53. if ($result === false) {
  54. \Easemob\exception($path . " 目录无写入权限");
  55. }
  56. return true;
  57. }
  58. }