Cache.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Jaeger <JaegerCode@gmail.com>
  5. * Date: 18/12/11
  6. * Time: 下午6:39
  7. */
  8. namespace Jaeger;
  9. use Cache\Adapter\Common\AbstractCachePool;
  10. use Cache\Adapter\Filesystem\FilesystemCachePool;
  11. use League\Flysystem\Adapter\Local;
  12. use League\Flysystem\Filesystem;
  13. class Cache extends GHttp
  14. {
  15. public static function remember($name, $arguments)
  16. {
  17. $cachePool = null;
  18. $cacheConfig = self::initCacheConfig($arguments);
  19. if (empty($cacheConfig['cache'])) {
  20. return self::$name(...$arguments);
  21. }
  22. if (is_string($cacheConfig['cache'])) {
  23. $filesystemAdapter = new Local($cacheConfig['cache']);
  24. $filesystem = new Filesystem($filesystemAdapter);
  25. $cachePool = new FilesystemCachePool($filesystem);
  26. }else if ($cacheConfig['cache'] instanceof AbstractCachePool) {
  27. $cachePool = $cacheConfig['cache'];
  28. }
  29. $cacheKey = self::getCacheKey($name,$arguments);
  30. $data = $cachePool->get($cacheKey);
  31. if(empty($data)) {
  32. $data = self::$name(...$arguments);
  33. if(!empty($data)) {
  34. $cachePool->set($cacheKey,$data,$cacheConfig['cache_ttl']);
  35. }
  36. }
  37. return $data;
  38. }
  39. protected static function initCacheConfig($arguments)
  40. {
  41. $cacheConfig = [
  42. 'cache' => null,
  43. 'cache_ttl' => null
  44. ];
  45. if(!empty($arguments[2])) {
  46. $cacheConfig = array_merge([
  47. 'cache' => null,
  48. 'cache_ttl' => null
  49. ],$arguments[2]);
  50. }
  51. return $cacheConfig;
  52. }
  53. protected static function getCacheKey($name, $arguments)
  54. {
  55. return md5($name.'_'.json_encode($arguments));
  56. }
  57. }