1 <?php
2 3 4 5 6 7
8
9 namespace Cross\Cache\Driver;
10
11 use Cross\Exception\CoreException;
12 use Cross\I\CacheInterface;
13
14 15 16 17 18
19 class FileCacheDriver implements CacheInterface
20 {
21 22 23 24 25
26 private $cache_path;
27
28 function __construct($cache_path)
29 {
30 $cache_path = rtrim($cache_path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
31 $this->cache_path = $cache_path;
32 }
33
34 35 36 37 38 39
40 function get($key = '')
41 {
42 $cache_file = $this->cache_path . $key;
43 if (!file_exists($cache_file)) {
44 return false;
45 }
46
47 return file_get_contents($cache_file);
48 }
49
50 51 52 53 54 55 56 57
58 function set($key, $value)
59 {
60 $cacheFile = $this->cache_path . $key;
61 if (!file_exists($cacheFile)) {
62 $filePath = dirname($cacheFile);
63 if (!is_dir($filePath)) {
64 $createDir = mkdir($filePath, 0755, true);
65 if (!$createDir) {
66 throw new CoreException('创建缓存目录失败');
67 }
68 }
69 }
70
71 file_put_contents($cacheFile, $value, LOCK_EX);
72 }
73 }
74