File.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. <?php
  2. namespace Lib\StoreDriver;
  3. /**
  4. *
  5. * 这里用php数组文件来存储数据,
  6. * 为了获取高性能需要用类似memcache的存储
  7. * @author walkor <workerman.net>
  8. *
  9. */
  10. class File
  11. {
  12. // 为了避免频繁读取磁盘,增加了缓存机制
  13. protected $dataCache = array();
  14. // 上次缓存时间
  15. protected $lastCacheTime = 0;
  16. // 保存数据的文件
  17. protected $dataFile = '';
  18. // 打开文件的句柄
  19. protected $dataFileHandle = null;
  20. // 缓存过期时间
  21. const CACHE_EXP_TIME = 1;
  22. /**
  23. * 构造函数
  24. * @param 配置名 $config_name
  25. */
  26. public function __construct($config_name)
  27. {
  28. $this->dataFile = \Config\Store::$storePath . "/$config_name.store.cache.php";
  29. if(!is_file($this->dataFile))
  30. {
  31. touch($this->dataFile);
  32. }
  33. $this->dataFileHandle = fopen($this->dataFile, 'r+');
  34. if(!$this->dataFileHandle)
  35. {
  36. $error_msg = "can not fopen($this->dataFile, 'r+')";
  37. throw new \Exception($error_msg);
  38. }
  39. }
  40. /**
  41. * 设置
  42. * @param string $key
  43. * @param mixed $value
  44. * @param int $ttl
  45. * @return number
  46. */
  47. public function set($key, $value, $ttl = 0)
  48. {
  49. flock($this->dataFileHandle, LOCK_EX);
  50. $this->readDataFromDisk();
  51. $this->dataCache[$key] = $value;
  52. $ret = $this->writeToDisk();
  53. flock($this->dataFileHandle, LOCK_UN);
  54. return $ret;
  55. }
  56. /**
  57. * 读取
  58. * @param string $key
  59. * @param bool $use_cache
  60. * @return Ambigous <NULL, multitype:>
  61. */
  62. public function get($key, $use_cache = true)
  63. {
  64. if(!$use_cache || time() - $this->lastCacheTime > self::CACHE_EXP_TIME)
  65. {
  66. flock($this->dataFileHandle, LOCK_EX);
  67. $this->readDataFromDisk();
  68. flock($this->dataFileHandle, LOCK_UN);
  69. }
  70. return isset($this->dataCache[$key]) ? $this->dataCache[$key] : null;
  71. }
  72. /**
  73. * 删除
  74. * @param string $key
  75. * @return number
  76. */
  77. public function delete($key)
  78. {
  79. flock($this->dataFileHandle, LOCK_EX);
  80. $this->readDataFromDisk();
  81. unset($this->dataCache[$key]);
  82. $ret = $this->writeToDisk();
  83. flock($this->dataFileHandle, LOCK_UN);
  84. return $ret;
  85. }
  86. /**
  87. * 写入磁盘
  88. * @return number
  89. */
  90. protected function writeToDisk()
  91. {
  92. return file_put_contents($this->dataFile, "<?php \n return " . var_export($this->dataCache, true). ';');
  93. }
  94. /**
  95. * 从磁盘读
  96. */
  97. protected function readDataFromDisk()
  98. {
  99. $cache = include $this->dataFile;
  100. if(is_array($cache))
  101. {
  102. $this->dataCache = $cache;
  103. }
  104. $this->lastCacheTime = time();
  105. }
  106. }