ThinkPHP 3.2.3实现页面静态化功能的方法详解

2019-05-01 06:02:22王旭

模版文件 /Application/Home/View/Index/index_php.php

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Document</title>
</head>
<body>
 <volist name="list" id="vo">
  {$vo.cat_name}<br />
 </volist> 
</body>
</html>

在执行 http://ServerName/Home/Index/makehtml_homepage ,即手动生成静态首页后,在 /Application/Home/View/Index/ 路径下生成了静态文件:index_html.html,根据配置文件中设置的 INDEX_MODE 为静态,访问 http://ServerName 实际访问的就是新生成的静态文件。

ThinkPHP 也自带了生成静态文件的方法 buildHtml,使用方法是 buildHtml('生成的静态文件名称', '生成的静态文件路径', '指定要调用的模板文件');

方法在 /ThinkPHP/Library/Think/Controller.class.php,Line 86:

/**
  * 创建静态页面
  * @access protected
  * @htmlfile 生成的静态文件名称
  * @htmlpath 生成的静态文件路径
  * @param string $templateFile 指定要调用的模板文件
  * 默认为空 由系统自动定位模板文件
  * @return string
  */
 protected function buildHtml($htmlfile='',$htmlpath='',$templateFile='') {
  $content = $this->fetch($templateFile);
  $htmlpath = !empty($htmlpath)?$htmlpath:HTML_PATH;
  $htmlfile = $htmlpath.$htmlfile.C('HTML_FILE_SUFFIX');
  Storage::put($htmlfile,$content,'html');
  return $content;
 }

其中 Storage 类在 /ThinkPHP/Library/Think/Storage.class.php

<?php
// +----------------------------------------------------------------------
// | TOPThink [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://topthink.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace Think;
// 分布式文件存储类
class Storage {

 /**
  * 操作句柄
  * @var string
  * @access protected
  */
 static protected $handler ;

 /**
  * 连接分布式文件系统
  * @access public
  * @param string $type 文件类型
  * @param array $options 配置数组
  * @return void
  */
 static public function connect($type='File',$options=array()) {
  $class = 'ThinkStorageDriver'.ucwords($type);
  self::$handler = new $class($options);
 }

 static public function __callstatic($method,$args){
  //调用缓存驱动的方法
  if(method_exists(self::$handler, $method)){
   return call_user_func_array(array(self::$handler,$method), $args);
  }
 }
}

默认的文件类型是 File,所以实例化的类的地址在 /ThinkPHP/Library/Think/Storage/Driver/File.class.php

相关文章 大家在看