


Smarty configuration and advanced caching technology sharing_PHP tutorial
Foreword
Smarty is an excellent PHP template engine that separates logical code and user interface.
Learning and using Smarty, not applying its caching technology is a big loss. It can cache the HMTL file that the user finally sees into a static HTML page. When setting the cache attribute of Smarty When it is true, the user's WEB request will be directly converted into this static HTML file within the cachetime period set by Smarty. This is equivalent to calling a static HTML file, which reduces a lot of burden on the backend server.
Download and Configuration
Official download: Smarty Download
After downloading, unzip it to the file directory of your project.
require('../libs/Smarty.class.php') ;
$smarty = new Smarty;
//$smarty->force_compile = true; //Force compilation
$smarty->debugging = true; //Debugging
$smarty-> ;caching = true; //Enable caching
$smarty->cache_lifetime = 120; //Cache survival time (seconds)
$smarty->cache_dir = MY_SMARTY_DIR . '/cache/' ; //Set the cache storage path
Note: If you find that the cache file changes every time you browse, please see Smarty's force_compile, which will force Smarty to (re)compile the template every time it is called. This setting is not restricted by $compile_check. By default, it is disabled. It is very convenient for development and debugging. But it must not be used in a production environment. If caching is enabled, the cache file will be regenerated each time.
$smarty->force_compile = false; //Force Compile
Smarty caching technology
Global cache
Local cache
insert method
Dynamic block method
Plug-in block method
Global caching technology
As the name suggests, global caching is to generate a cache file for the entire page, specify the survival time of the cache file, browse the entire page again within the specified time, and it will be read directly Cache files.
$smarty->caching = true; //Enable caching
$smarty ->cache_lifetime = 120; //Cache survival time (seconds)
Note: A template can only have one cache file. If your template has multiple pages, you must Set an ID for the cache. For example, a page has multiple articles:
http://website/index.php?p=1
http://website/index.php?p=2
//$_SERVER['REQUEST_URI'] method
//Copy the URL of the current page (including the following ? All parameters) are md5 encrypted
$url=md5($_SERVER['REQUEST_URI']);
//Set the cache file name
$smarty->display('index.tpl',$url );
Key point: A big reason for using caching technology is to reduce reading and writing to the database, so we have to use $smarty->isCached('index.tpl') To determine whether the cache exists, if it exists, do not operate the database again.
if(!$smarty->isCached('index.tpl')){
echo "ACACHE NO FOUND!";
$sql = "SELECT * FROM test";
$query = mysql_query($sql);
$row = mysql_fetch_row($query);
$smarty->assign("loaddatabase",$row[1]);
}
There is another problem here. If I change something in the database and want to update the display content, but the cache has not expired yet, what should I do?
$smarty->clearCache("index.tpl");
The clearCache above can solve this problem. Just call clearCache to clear the cache after updating the data.
PS: I am using the Smarty3 version. The names of many methods have changed in this version. If it is Smarty2, "Call of unknown method 'isCached'." will appear. Please use $smarty-> is_cached().
Smarty3:registerPlugin() and Smarty2:register_block() that appear later are also version issues.
Let’s take a look at the speed comparison with and without caching:
1. First time browsing, without caching, Total Time 0.01421
Partial caching technology
Partial caching = partial caching, that is, in the cache of a page, not all caches are generated. You can customize a certain functional module not to generate cache, and it will be cached every time you browse. Update data;
For example: the web page displays the user's status, web page statistics, advertising banners, etc. These data are updated very quickly and are not suitable for caching. In this way, local caching will be useful.
There are 3 methods for local caching:
1. Insert method
The content contained in insert will not be cached, and the function will be re-executed every time the template is called.
Usage:
Note that the function name here must start with insert, and the name in the template corresponds to it.
index.php
//Define a time to test insert and The difference between ordinary assign
$date = date("Y-m-d H:i:s");
$smarty->assign("date", $date);
//insert
function insert_get_current_time($date){
return date("Y-m-d H:i:s");
}
index.tpl
nocache:{insert name="get_current_time"}
cache: {$date}
[code]
Then look Generated cache file: Conclusion insert will re-execute the function every time the template is called
nocache:),$_smarty_tpl);?> ;
cache: 2012-06-04 15:46:52
This method is simple, but if the content to be displayed is a large piece, it should not be used.
2. Dynamic block method
Custom block in php
index.php
[code]
//smarty 3
// function declaration
function smarty_block_nocache ($param,$content,$smarty)
{
return $content;
}
// register with smarty
$smarty->registerPlugin("function", "nocache", "smarty_block_nocache");
As mentioned at the beginning, Smarty3 uses registerPlugin, and Smarty2 uses register_block
index.tpl
{ nocache}{$date}{/nocache}
Then look at the cache file and conclude that $date will be re-executed every time the template is called
[/code]
value;?>
3. Plug-in block method
This method is similar to the second method, except that the custom block in php is placed in the plugins folder in the smarty directory.
Create a file block.nocache.php in the Smarty/plugins directory with the following content:
function smarty_block_nocache($param, $content, $smarty)
{
return $content;
}
?>
[code]
The use in tpl template is the same as the second method
Summary
It can be concluded that Smarty caching technology can greatly improve the speed and quality of the website, and its usage is relatively simple.
The final reminder is that although the extension of the cache file generated by Smarty is php, it will not be parsed as php code.
Author: That moment

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

To work on file upload we are going to use the form helper. Here, is an example for file upload.

Validator can be created by adding the following two lines in the controller.

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks.

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an
