search
HomeBackend DevelopmentPHP TutorialDetailed explanation of pure static and pseudo-static usage of PHP page staticization

Detailed explanation of pure static and pseudo-static usage of PHP page staticization

The examples in this article describe the pure static and pseudo-static usage of PHP page staticization. Share it with everyone for your reference, the details are as follows:

Why do we need to make the page static?

When a user accesses a not frequently updated Web page, PHP is instructed to parse the php script file and query the data required for the page from the database , then render the page template, and finally display a finished page to the user. A single request is very simple and fast for the server to handle, but what if thousands of different users request the page at the same time? This is undoubtedly a waste of resources, and this is the purpose of doing static.

Staticization is divided into pure static and pseudo-static, and pure static is divided into partial pure static and total pure static.

Related learning recommendations: PHP programming from entry to proficiency

pseudo-static

Pseudo-static, as the name suggests, is not true The static page is disguised. For example, for a web site with PHP as the back-end language, under normal circumstances its URL should be similar to http://www.example.com/index.php. When we do pseudo-static processing , when you visit the same page, the URL displayed may be http://www.example.com/index.html. Its function is to simplify routing and be better indexed by search engines. This method can also be used when you don’t want users to know your back-end language. The routing and redirection knowledge is designed here and will not be explained in detail.

Pure static

  • Partial pure static

A page usually consists of multiple parts, such as a blog, which may consist of text, categories, friendship It is composed of links, columns and other parts. Partial staticization can be used when some parts are updated frequently and some parts are updated infrequently.

  • All purely static

It is easy to understand after reading the previous content. This method is used when all the content of a page is not updated frequently.

Static page implementation principle

The first thing I want to talk about is a thing called a buffer. Let's give a simple example to illustrate its role: when we edit a document, the system will not write to the disk before we save it, but will write it to the buffer. When the buffer is full or a save operation is performed, , the data will be written to the disk. For PHP, every output operation like echo is also written to the php buffer first. The data will not be displayed on the browser until the script is executed or a forced output caching operation is performed.
       Here we are going to do something about this buffer. Before php outputs the content, we take out the content of the buffer (here is the rendered template content), and then write it into a static file and set it Expiration time, when the user visits the page next time, if the static file exists and is within the validity period, we will directly display the static file to the user, otherwise we will rewrite the static file.

The code implements

database connection, using the singleton mode.

Database.php

<?php
class Database {
  //用于保存实例化对象
  private static $instance;
  //用于保存数据库句柄
  private $db = null;

  //禁止直接实例化,负责数据库连接,将数据库连接句柄保存至私有变量$db
  private function __construct($options) {
    $this->db = mysqli_connect($options[&#39;db_host&#39;], $options[&#39;db_user&#39;], $options[&#39;db_password&#39;], $options[&#39;db_database&#39;]);
  }

  //负责实例化数据库类,返回实例化后的对象
  public static function getInstance($options) {
    if (!(self::$instance instanceof self)) {
      self::$instance = new self($options);
    }
    return self::$instance;
  }

  //获取数据库连接句柄
  public function db() {
    return $this->db;
  }

  //禁止克隆
  private function __clone() {
    // TODO: Implement __clone() method.
  }

  //禁止重构
  private function __wakeup() {
    // TODO: Implement __wakeup() method.
  }
}

Used for static pages

Cache.php

<?php
class Cache {
  public function index($options) {
    //判断文件是否存在,判断是否过期
    if (is_file(&#39;shtml/index.shtml&#39;) && (time() - filemtime(&#39;shtml/index.shtml&#39;) < 300)) {
      require_once (&#39;index.shtml&#39;);
    }else {
      require_once (&#39;Database.php&#39;);
      $con = Database::getInstance($options)->db();
      $sql = "SELECT * FROM pro_test";
      $exe_res = mysqli_query($con, $sql);
      $res = mysqli_fetch_all($exe_res);
      try{
        if (!$res) {
          throw new Exception("no result");
        }
      }catch (Exception $e) {
        echo &#39;Message: &#39; .$e->getMessage();
      }
      //开启缓存区,这后面的内容都会进缓存区
      ob_start();
      //引入模板文件(模板会渲染数据)
      require_once (&#39;templates/index.php&#39;);
      //取出缓存区内容(在这里是渲染后的模板),将其保存(默认会覆盖原来的)为index.shtml(static html)
      file_put_contents(&#39;shtml/index.shtml&#39;, ob_get_contents());
    }
  }
}
//数据库配置信息
$options = [
  &#39;db_host&#39; => &#39;mysql&#39;,
  &#39;db_user&#39; => &#39;root&#39;,
  &#39;db_password&#39; => &#39;localhost&#39;,
  &#39;db_database&#39; => &#39;pro_shop&#39;,
];
$obj = new Cache();
$obj->index($options);

template/index.php

<!DOCTYPE>
<html>
<head>
  <meta charset="UTF-8">
  <title>首页</title>
</head>
<body>
<?php foreach ($res as $item) {?>
<p>姓名:<?php echo $item[1]?></p>
<p>密码:<?php echo $item[2]?></p>
<?php }?>
</body>
</html>

Browser accesslocalhost/Cache.php

The above is the detailed content of Detailed explanation of pure static and pseudo-static usage of PHP page staticization. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:jb51. If there is any infringement, please contact admin@php.cn delete
PHP vs. Python: Understanding the DifferencesPHP vs. Python: Understanding the DifferencesApr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: Is It Dying or Simply Adapting?PHP: Is It Dying or Simply Adapting?Apr 11, 2025 am 12:13 AM

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.

The Future of PHP: Adaptations and InnovationsThe Future of PHP: Adaptations and InnovationsApr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

When would you use a trait versus an abstract class or interface in PHP?When would you use a trait versus an abstract class or interface in PHP?Apr 10, 2025 am 09:39 AM

In PHP, trait is suitable for situations where method reuse is required but not suitable for inheritance. 1) Trait allows multiplexing methods in classes to avoid multiple inheritance complexity. 2) When using trait, you need to pay attention to method conflicts, which can be resolved through the alternative and as keywords. 3) Overuse of trait should be avoided and its single responsibility should be maintained to optimize performance and improve code maintainability.

What is a Dependency Injection Container (DIC) and why use one in PHP?What is a Dependency Injection Container (DIC) and why use one in PHP?Apr 10, 2025 am 09:38 AM

Dependency Injection Container (DIC) is a tool that manages and provides object dependencies for use in PHP projects. The main benefits of DIC include: 1. Decoupling, making components independent, and the code is easy to maintain and test; 2. Flexibility, easy to replace or modify dependencies; 3. Testability, convenient for injecting mock objects for unit testing.

Explain the SPL SplFixedArray and its performance characteristics compared to regular PHP arrays.Explain the SPL SplFixedArray and its performance characteristics compared to regular PHP arrays.Apr 10, 2025 am 09:37 AM

SplFixedArray is a fixed-size array in PHP, suitable for scenarios where high performance and low memory usage are required. 1) It needs to specify the size when creating to avoid the overhead caused by dynamic adjustment. 2) Based on C language array, directly operates memory and fast access speed. 3) Suitable for large-scale data processing and memory-sensitive environments, but it needs to be used with caution because its size is fixed.

How does PHP handle file uploads securely?How does PHP handle file uploads securely?Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

What is the Null Coalescing Operator (??) and Null Coalescing Assignment Operator (??=)?What is the Null Coalescing Operator (??) and Null Coalescing Assignment Operator (??=)?Apr 10, 2025 am 09:33 AM

In JavaScript, you can use NullCoalescingOperator(??) and NullCoalescingAssignmentOperator(??=). 1.??Returns the first non-null or non-undefined operand. 2.??= Assign the variable to the value of the right operand, but only if the variable is null or undefined. These operators simplify code logic, improve readability and performance.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),