Home Backend Development PHP Tutorial ThinkPHP 3.2.3 Method to implement page static function

ThinkPHP 3.2.3 Method to implement page static function

May 10, 2018 am 10:16 AM
php thinkphp

这篇文章主要介绍了关于ThinkPHP 3.2.3实现页面静态化功能的方法,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下

页面静态化是我们在开发网站的时候经常需要的一个功能,下面这篇文章主要给大家介绍了关于ThinkPHP 3.2.3实现页面静态化功能的方法,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴,下面来一起看看吧。

前言

大家都知道PHP 的页面静态化有多种实现方式,比如使用输出缓冲(output buffering),该种方式是把数据缓存在 PHP 的缓冲区(内存)中,下一次取数据时直接从缓冲区中读取数据,从而避免了脚本的编译和访问数据库等过程;另一种方式是直接生成静态的 HTML 文件,使用文件读写函数来实现,一些内容不经常改动的页面可以使用静态页面,访客访问到的页面就是真实的 HTML 页面,一些常见的 CMS 会使用该种方法。

以第二种方法为例,参考 DedeCMS 5.7 的静态化功能,在 ThinkPHP 3.2.3 下实现该方法。由于 ThinkPHP 是单入口系统,而且每一个页面都要对应控制器中的某个方法,因此不能直接把静态文件的地址作为实际访问的地址,而是需要在控制器中以模版加载的方式读取静态文件。

首页静态化的实现

在 DedeCMS 5.7 中,可以生成静态的首页、栏目页和文章页。其中首页的生成在后台的“生成”栏目进行设置,包括模板的选择、首页静态文件的存放路径以及首页模式(使用动态首页还是静态首页),DedeCMS 还专门为首页的设置设计了一张表 dede_homepageset,包含的字段包括 templet(模板位置)、position(首页静态文件的路径)、showmod(首页模式),通过在后台进行设置与生成,来控制网站首页使用动态首页还是静态首页,用到的核心文件是 \dede\makehtml_homepage.php。

流程大致是:

① 在后台选择生成静态页面时,通过表单向 makehtml_homepage.php 发送请求,参数包括 dede_homepageset 的所有字段

② 根据传递参数中的 templet、position、showmod 更新 dede_homepageset 表

③ 如果 showmod 是使用静态,加载模板,把模板保存为静态文件。使用的方法是 fopen(),fwrite() 和 fclose(),非常简单

④ 生成了静态页面之后,访客访问的就直接是静态的 index.html,如果首页发生了改变,则手动在后台重新生成一下首页

在 ThinkPHP 中可以这样设计:

config.php

1

2

3

4

5

6

<?php

return array(

 //&#39;配置项&#39;=>&#39;配置值&#39;

 &#39;INDEX_MOD&#39;=>1,//首页模式 0-动态模式 1-静态模式

 &#39;INDEX_HTML_FILE&#39;=>__ROOT__.&#39;Application/Home/View/Index/index_html.html&#39;,//静态首页地址

);

Copy after login

/Application/Home/Controller/IndexController.php

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

<?php

namespace Home\Controller;

use Think\Controller;

class IndexController extends Controller {

  

 //首页

 public function index() {

  if(1 == C(&#39;INDEX_MOD&#39;)) {

   //静态

   $this->display(&#39;index_html&#39;);

  } else {

   //动态

   $list = M(&#39;category&#39;)->select();

   $this->assign(&#39;list&#39;, $list);

   $this->display(&#39;index_php&#39;);

  }

 }

  

 //根据动态首页的内容生成静态页面

 public function makehtml_homepage() {

  $homepage = &#39;http://&#39;.$_SERVER[&#39;HTTP_HOST&#39;].U(&#39;Home/Index/index_php&#39;);

  $content = @file_get_contents($homepage);

  file_put_contents(C(&#39;INDEX_HTML_FILE&#39;), $content);

 }

  

 //动态首页数据

 public function index_php() {

  C(&#39;INDEX_MOD&#39;, 0);

  $this->index();

 }

}

Copy after login

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

1

2

3

4

5

6

7

8

9

10

11

12

<!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>

Copy after login

在执行 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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

/**

  * 创建静态页面

  * @access protected

  * @htmlfile 生成的静态文件名称

  * @htmlpath 生成的静态文件路径

  * @param string $templateFile 指定要调用的模板文件

  * 默认为空 由系统自动定位模板文件

  * @return string

  */

 protected function buildHtml($htmlfile=&#39;&#39;,$htmlpath=&#39;&#39;,$templateFile=&#39;&#39;) {

  $content = $this->fetch($templateFile);

  $htmlpath = !empty($htmlpath)?$htmlpath:HTML_PATH;

  $htmlfile = $htmlpath.$htmlfile.C(&#39;HTML_FILE_SUFFIX&#39;);

  Storage::put($htmlfile,$content,&#39;html&#39;);

  return $content;

 }

Copy after login

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

<?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=&#39;File&#39;,$options=array()) {

  $class = &#39;Think\\Storage\\Driver\\&#39;.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);

  }

 }

}

Copy after login

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

<?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\Storage\Driver;

use Think\Storage;

// 本地文件写入存储类

class File extends Storage{

 

 private $contents=array();

 

 /**

  * 架构函数

  * @access public

  */

 public function __construct() {

 }

 

 /**

  * 文件内容读取

  * @access public

  * @param string $filename 文件名

  * @return string 

  */

 public function read($filename,$type=&#39;&#39;){

  return $this->get($filename,&#39;content&#39;,$type);

 }

 

 /**

  * 文件写入

  * @access public

  * @param string $filename 文件名

  * @param string $content 文件内容

  * @return boolean  

  */

 public function put($filename,$content,$type=&#39;&#39;){

  $dir   = dirname($filename);

  if(!is_dir($dir))

   mkdir($dir,0755,true);

  if(false === file_put_contents($filename,$content)){

   E(L(&#39;_STORAGE_WRITE_ERROR_&#39;).&#39;:&#39;.$filename);

  }else{

   $this->contents[$filename]=$content;

   return true;

  }

 }

 

 /**

  * 文件追加写入

  * @access public

  * @param string $filename 文件名

  * @param string $content 追加的文件内容

  * @return boolean 

  */

 public function append($filename,$content,$type=&#39;&#39;){

  if(is_file($filename)){

   $content = $this->read($filename,$type).$content;

  }

  return $this->put($filename,$content,$type);

 }

 

 /**

  * 加载文件

  * @access public

  * @param string $filename 文件名

  * @param array $vars 传入变量

  * @return void 

  */

 public function load($_filename,$vars=null){

  if(!is_null($vars))

   extract($vars, EXTR_OVERWRITE);

  include $_filename;

 }

 

 /**

  * 文件是否存在

  * @access public

  * @param string $filename 文件名

  * @return boolean 

  */

 public function has($filename,$type=&#39;&#39;){

  return is_file($filename);

 }

 

 /**

  * 文件删除

  * @access public

  * @param string $filename 文件名

  * @return boolean 

  */

 public function unlink($filename,$type=&#39;&#39;){

  unset($this->contents[$filename]);

  return is_file($filename) ? unlink($filename) : false;

 }

 

 /**

  * 读取文件信息

  * @access public

  * @param string $filename 文件名

  * @param string $name 信息名 mtime或者content

  * @return boolean 

  */

 public function get($filename,$name,$type=&#39;&#39;){

  if(!isset($this->contents[$filename])){

   if(!is_file($filename)) return false;

   $this->contents[$filename]=file_get_contents($filename);

  }

  $content=$this->contents[$filename];

  $info = array(

   &#39;mtime&#39;  => filemtime($filename),

   &#39;content&#39; => $content

  );

  return $info[$name];

 }

}

Copy after login

可以看到 get 和 put 方法所使用的方法是 file_get_contents() file_put_contents()

相关推荐:

thinkphp5实现分页功能的方法介绍

The above is the detailed content of ThinkPHP 3.2.3 Method to implement page static function. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Why Use PHP? Advantages and Benefits Explained Why Use PHP? Advantages and Benefits Explained Apr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

The Continued Use of PHP: Reasons for Its Endurance The Continued Use of PHP: Reasons for Its Endurance Apr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

See all articles