PHP緩衝之檔案快取

來源:互聯網
上載者:User
1、PHP檔案快取內容儲存格式
PHP檔案快取內容儲存格式主要有三種:
(1)變數 var_export 格式化成PHP正常的賦值書寫格式;
(2)變數 serialize 序列化之後儲存,用的時候還原序列化;
(3)變數 json_encode格式化之後儲存,用的時候json_decode
互連網上測試結果是:serialize格式的檔案解析效率大於Json,Json的解析效率大於PHP正常賦值。
所以我們要是快取資料建議採用序列化的形式解析資料會更快。

2、PHP檔案快取的簡單案例

[php] view plain copy print ?

  1. class Cache_Driver{
  2. //定義緩衝的路徑
  3. protected $_cache_path;
  4. //根據$config中的cache_path值擷取路徑資訊
  5. public function Cache_Driver($config)
  6. {
  7. if(is_array($config) && isset($config['cache_path']))
  8. {
  9. $this->_cache_path = $config['cache_path'];
  10. }
  11. else
  12. {
  13. $this->_cache_path = realpath(dirname(__FILE__)."/")."/cache/";
  14. }
  15. }
  16. //判斷key值對應的檔案是否存在,如果存在,讀取value值,value以序列化儲存
  17. public function get($id)
  18. {
  19. if ( ! file_exists($this->_cache_path.$id))
  20. {
  21. return FALSE;
  22. }
  23. $data = @file_get_contents($this->_cache_path.$id);
  24. $data = unserialize($data);
  25. if(!is_array($data) || !isset($data['time']) || !isset($data['ttl']))
  26. {
  27. return FALSE;
  28. }
  29. if ($data['ttl'] > 0 && time() > $data['time'] + $data['ttl'])
  30. {
  31. @unlink($this->_cache_path.$id);
  32. return FALSE;
  33. }
  34. return $data['data'];
  35. }
  36. //設定緩衝資訊,根據key值,產生相應的快取檔案
  37. public function set($id, $data, $ttl = 60)
  38. {
  39. $contents = array(
  40. 'time' => time(),
  41. 'ttl' => $ttl,
  42. 'data' => $data
  43. );
  44. if (@file_put_contents($this->_cache_path.$id, serialize($contents)))
  45. {
  46. @chmod($this->_cache_path.$id, 0777);
  47. return TRUE;
  48. }
  49. return FALSE;
  50. }
  51. //根據key值,刪除快取檔案
  52. public function delete($id)
  53. {
  54. return @unlink($this->_cache_path.$id);
  55. }
  56. public function clean()
  57. {
  58. $dh = @opendir($this->_cache_path);
  59. if(!$dh)
  60. return FALSE;
  61. while ($file = @readdir($dh))
  62. {
  63. if($file == "." || $file == "..")
  64. continue;
  65. $path = $this->_cache_path."/".$file;
  66. if(is_file($path))
  67. @unlink($path);
  68. }
  69. @closedir($dh);
  70. return TRUE;
  71. }
  72. }
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.