FileCache.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. /**
  3. * Cache with file system
  4. */
  5. class FileCache extends CacheAbstract{
  6. protected $cacheDirCreated; // boolean to avoid always chck dir cache existance
  7. public function loadData(){
  8. $this->isPrepareCache();
  9. $datas = unserialize(file_get_contents($this->getCacheFile()));
  10. $items = array();
  11. foreach($datas as $aData){
  12. $item = new \Item();
  13. foreach($aData as $name => $value){
  14. $item->$name = $value;
  15. }
  16. $items[] = $item;
  17. }
  18. return $items;
  19. }
  20. public function saveData($datas){
  21. $this->isPrepareCache();
  22. //Re-encode datas to UTF-8
  23. //$datas = Cache::utf8_encode_deep($datas);
  24. $writeStream = file_put_contents($this->getCacheFile(), serialize($datas));
  25. if(!$writeStream) {
  26. throw new \Exception("Cannot write the cache... Do you have the right permissions ?");
  27. }
  28. return $this;
  29. }
  30. public function getTime(){
  31. $this->isPrepareCache();
  32. $cacheFile = $this->getCacheFile();
  33. if( file_exists($cacheFile) ){
  34. return filemtime($cacheFile);
  35. }
  36. return false;
  37. }
  38. /**
  39. * Cache is prepared ?
  40. * Note : Cache name is based on request information, then cache must be prepare before use
  41. * @return \Exception|true
  42. */
  43. protected function isPrepareCache(){
  44. if( is_null($this->param) ){
  45. throw new \Exception('Please feed "prepare" method before try to load');
  46. }
  47. return true;
  48. }
  49. /**
  50. * Return cache path (and create if not exist)
  51. * @return string Cache path
  52. */
  53. protected function getCachePath(){
  54. $cacheDir = __DIR__ . '/../cache/'; // FIXME : configuration ?
  55. // FIXME : implement recursive dir creation
  56. if( is_null($this->cacheDirCreated) && !is_dir($cacheDir) ){
  57. $this->cacheDirCreated = true;
  58. mkdir($cacheDir,0705);
  59. chmod($cacheDir,0705);
  60. }
  61. return $cacheDir;
  62. }
  63. /**
  64. * Get the file name use for cache store
  65. * @return string Path to the file cache
  66. */
  67. protected function getCacheFile(){
  68. return $this->getCachePath() . $this->getCacheName();
  69. }
  70. /**
  71. * Determines file name for store the cache
  72. * return string
  73. */
  74. protected function getCacheName(){
  75. $this->isPrepareCache();
  76. $stringToEncode = $_SERVER['REQUEST_URI'] . http_build_query($this->param);
  77. return hash('sha1', $stringToEncode) . '.cache';
  78. }
  79. }