1 <?php
2 3 4 5 6 7
8
9 namespace Cross\Cache\Request;
10
11 use Cross\I\RequestCacheInterface;
12 use Cross\Cache\Driver\RedisDriver;
13 use Cross\Exception\CoreException;
14
15 16 17 18 19
20 class RedisCache implements RequestCacheInterface
21 {
22 23 24
25 protected $config;
26
27 28 29 30 31
32 protected $cacheKey;
33
34 35 36 37 38
39 protected $expireTime = 3600;
40
41 42 43
44 protected $compress = false;
45
46 47 48
49 protected $driver;
50
51 52 53 54 55 56
57 function __construct(array $option)
58 {
59 if (empty($option['key'])) {
60 throw new CoreException('请指定缓存KEY');
61 }
62
63 if (isset($option['expire_time'])) {
64 $this->expireTime = &$option['expire_time'];
65 }
66
67 if (isset($option['compress'])) {
68 $this->compress = &$option['compress'];
69 }
70
71 $this->cacheKey = &$option['key'];
72 $this->driver = new RedisDriver($option);
73 }
74
75 76 77 78 79 80
81 function set($value)
82 {
83 if ($this->compress) {
84 $value = gzcompress($value);
85 }
86
87 $this->driver->setex($this->cacheKey, $this->expireTime, $value);
88 }
89
90 91 92 93 94
95 function get()
96 {
97 $content = $this->driver->get($this->cacheKey);
98 if ($this->compress) {
99 $content = gzuncompress($content);
100 }
101
102 return $content;
103 }
104
105 106 107 108 109
110 function isValid()
111 {
112 return $this->driver->ttl($this->cacheKey) > 0;
113 }
114
115 116 117 118 119
120 function setConfig(array $config = array())
121 {
122 $this->config = $config;
123 }
124
125 126 127 128 129
130 function getConfig()
131 {
132 return $this->config;
133 }
134 }
135