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