File.php 2.2 KB

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