File.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. * @param string $cacheFile 缓存的文件名
  19. * @param string $content 缓存的内容
  20. * @return void|array
  21. */
  22. public function write($cacheFile, $content)
  23. {
  24. // 检测模板目录
  25. $dir = dirname($cacheFile);
  26. if (!is_dir($dir)) {
  27. mkdir($dir, 0755, true);
  28. }
  29. // 生成模板缓存文件
  30. if (false === file_put_contents($cacheFile, $content)) {
  31. throw new Exception('cache write error:' . $cacheFile, 11602);
  32. }
  33. }
  34. /**
  35. * 读取编译编译
  36. * @param string $cacheFile 缓存的文件名
  37. * @param array $vars 变量数组
  38. * @return void
  39. */
  40. public function read($cacheFile, $vars = [])
  41. {
  42. $this->cacheFile = $cacheFile;
  43. if (!empty($vars) && is_array($vars)) {
  44. // 模板阵列变量分解成为独立变量
  45. extract($vars, EXTR_OVERWRITE);
  46. }
  47. //载入模版缓存文件
  48. include $this->cacheFile;
  49. }
  50. /**
  51. * 检查编译缓存是否有效
  52. * @param string $cacheFile 缓存的文件名
  53. * @param int $cacheTime 缓存时间
  54. * @return boolean
  55. */
  56. public function check($cacheFile, $cacheTime)
  57. {
  58. // 缓存文件不存在, 直接返回false
  59. if (!file_exists($cacheFile)) {
  60. return false;
  61. }
  62. if (0 != $cacheTime && $_SERVER['REQUEST_TIME'] > filemtime($cacheFile) + $cacheTime) {
  63. // 缓存是否在有效期
  64. return false;
  65. }
  66. return true;
  67. }
  68. }