Home php教程 php手册 Smarty的配置与高级缓存技术分享

Smarty的配置与高级缓存技术分享

Jun 13, 2016 pm 12:00 PM
php smarty and point share Preface it engine technology yes template of cache Configuration advanced

前言

Smarty 是一个出色的PHP模板引擎,它分离了逻辑代码和user interface。

学习和使用Smarty,没有应用到它的缓存技术是一个很大的损失,它可以将用户最终看到的HMTL文件缓存成一个静态的HTML页,当设定Smarty的cache属性为true时,在Smarty设定的cachetime期内将用户的WEB请求直接转换到这个静态的HTML文件中来,这相当于调用一个静态的HTML文件,给后台服务器减少很多负担。

下载与配置

官方下载:Smarty Download

下载完后,解压到自己项目的文件目录下。

复制代码 代码如下:


require('../libs/Smarty.class.php');
$smarty = new Smarty;
//$smarty->force_compile = true; //强迫编译
$smarty->debugging = true; //调试
$smarty->caching = true; //开启缓存
$smarty->cache_lifetime = 120; //缓存存活时间(秒)

$smarty->cache_dir = MY_SMARTY_DIR . '/cache/' ; //设置缓存的存放路径


注意:如果你发现缓存文件每次浏览都会发生改变,请看 Smarty的 force_compile , 它会强迫Smarty每次调用(重新)编译模板。这项设置不受$compile_check的限制。默认情况下,它是无效的。它对于开发和调试很方便.但它决不能使用于产品环境下.如果启动了缓存,每次将会重新生成缓存文件.

$smarty->force_compile = false; //强迫编译

Smarty 缓存技术

全局缓存
局部缓存
insert 法
动态 block 法
插件 block 法

全局缓存技术

顾名思义,全局缓存就是把整个页面生成缓存文件,指定该缓存文件的存活时间,在指定时间内再次浏览整个页面,将直接读取缓存文件。

复制代码 代码如下:


$smarty->caching = true; //开启缓存
$smarty->cache_lifetime = 120; //缓存存活时间(秒)



注意:一个模板只能有一个缓存文件,如果您的模板存在多个页面的话,就要为缓存 设置一个ID。 例如一个页面有多个文章:

http://website/index.php?p=1
http://website/index.php?p=2

复制代码 代码如下:


//$_SERVER['REQUEST_URI']方法
//将当前页面的URL(包含?后面的所有参数)进行md5加密
$url=md5($_SERVER['REQUEST_URI']);
//设置缓存文件名
$smarty->display('index.tpl',$url);



重点:使用缓存技术,很大一个原因就是为了减少对数据库的读写,所以我们要用$smarty->isCached('index.tpl')来判断缓存是否存在,如果存在了就不要再次操作数据库。

复制代码 代码如下:


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]);
}


这里又有问题了,如果我改了数据库的某个内容,想更新显示内容,但是缓存又还没到消亡时间,那该肿么办呢?
$smarty->clearCache("index.tpl");
上面的clearCache可以解决这个问题,只要更新了数据后,调用clearCache清除一下缓存就可以了。

PS:我用的是Smarty3版本,这个版本很多方法的命名都发生变化了,如果是Smarty2的话会出现“Call of unknown method ‘isCached'.”,请使用$smarty->is_cached()。
后面出现的 Smarty3:registerPlugin(), Smarty2:register_block() 也一样是版本的问题。

下面我们来看一下有缓存和没缓存的速度比较:
1.首次浏览,没有缓存 Total Time 0.01421

2.第2次浏览,有缓存 Total Time 0.00308

这里我的index.php里只有几行代码,如果数据量大的话,就有明显的区别。

局部缓存技术

局部缓存 = 部分缓存, 就是一个页面的缓存中,并不是全都生成缓存,可以自定义设置某个功能模块不生成缓存,每次浏览都会更新数据;

例如:网页显示用户的状态、网页的统计数据、广告条等,这些数据的更新速度都非常快,不宜缓存,这样,局部缓存便有用武之地了。

局部缓存有3个方法:

一、insert法

insert 所包含的内容不会被缓存,每次调用该模板都会重新执行该函数.

使用方法:

注意这里的函数名一定要以insert开头,模板中的name与之对应。

index.php

复制代码 代码如下:


//定义一个时间来测试insert与普通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]
然后看生成的缓存文件:得出结论 insert 每次调用该模板都会重新执行该函数


nocache:),$_smarty_tpl);?>

cache: 2012-06-04 15:46:52

复制代码 代码如下:



这种方法简单,但是如果要显示的内容是一大块的,就不宜使用了。

二、动态block 法

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");


开始有提到过,Smarty3是用registerPlugin , Smarty2则是用register_block

index.tpl

{nocache}{$date}{/nocache}
然后看缓存文件 , 得出结论每次调用该模板都会重新执行$date
[/code]
tpl_vars['date']->value;?>

复制代码 代码如下:


三、插件block 法

这个方法和第2个差不多,只是把php中的自定义块,放到smarty目录中的plugins文件夹中。

在Smarty/plugins目录下建一个文件 block.nocache.php 内容如下:


function smarty_block_nocache($param, $content, $smarty)
{
return $content;
}
?>
[code]
tpl模板中的使用和第二个方法一样

总结
可以总结出Smarty缓存技术,能大大的提高网站的速度和质量,用法也比较简单。

最后提醒一下的就是, Smarty生成的缓存文件的扩展名虽然是php,但并不会被当作php代码来解析.

作者:那瞬间
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

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months 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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

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

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

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

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

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

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles