File.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace think\template\driver;
  12. use think\Exception;
  13. class File
  14. {
  15. protected $cacheFile;
  16. /**
  17. * 写入编译缓存
  18. * @access public
  19. * @param string $cacheFile 缓存的文件名
  20. * @param string $content 缓存的内容
  21. * @return void|array
  22. */
  23. public function write($cacheFile, $content)
  24. {
  25. // 检测模板目录
  26. $dir = dirname($cacheFile);
  27. if (!is_dir($dir)) {
  28. mkdir($dir, 0755, true);
  29. }
  30. // 生成模板缓存文件
  31. if (false === file_put_contents($cacheFile, $content)) {
  32. throw new Exception('cache write error:' . $cacheFile, 11602);
  33. }
  34. }
  35. /**
  36. * 读取编译编译
  37. * @access public
  38. * @param string $cacheFile 缓存的文件名
  39. * @param array $vars 变量数组
  40. * @return void
  41. */
  42. public function read($cacheFile, $vars = [])
  43. {
  44. $this->cacheFile = $cacheFile;
  45. if (!empty($vars) && is_array($vars)) {
  46. // 模板阵列变量分解成为独立变量
  47. extract($vars, EXTR_OVERWRITE);
  48. }
  49. //载入模版缓存文件
  50. include $this->cacheFile;
  51. }
  52. /**
  53. * 检查编译缓存是否有效
  54. * @access public
  55. * @param string $cacheFile 缓存的文件名
  56. * @param int $cacheTime 缓存时间
  57. * @return boolean
  58. */
  59. public function check($cacheFile, $cacheTime)
  60. {
  61. // 缓存文件不存在, 直接返回false
  62. if (!file_exists($cacheFile)) {
  63. return false;
  64. }
  65. if (0 != $cacheTime && time() > filemtime($cacheFile) + $cacheTime) {
  66. // 缓存是否在有效期
  67. return false;
  68. }
  69. return true;
  70. }
  71. }