Caching applications in the PHP smarty template engine

  • 2020-03-31 17:06:17
  • OfStack

1. Smarty cache configuration:

$smarty->cache-dir=" Directory name "; //Create the cache directory name
$smarty->caching=true; //Cache on. Cache is invalid when false
$smarty->cache_lifetime=60; //Cache time, in seconds

2. Use and clear Smarty cache

$marty->display("cache.tpl",cache_id); //Create a cache with an ID
$marty->clear_all_cache(); //Clear all caches
$marty->clear_cache("index.php"); //Clear the cache in index.php
$marty->clear_cache("index.php',cache_id); //Clear the cache of the specified ID in index.php

3. Local caching of Smarty
First: the insert_ function is not cached by default, and this property cannot be modified
Usage: examples
Index.php,
The function insert_get_time () {
The return date (" Y -m - d H: m: s ");
}
Index.html,
{insert name = "get_time}"

Second: smarty_block
Smarty_block_name ($params,$content, &$smarty){return $content; } //name represents the region name
Register block: $smarty - > Register_block (' name ', 'smarty_block_name, false); // the third parameter false means that the area is not cached
{name} {/name}
Write block plugin:
1) define a plugin function :block. Cacheless. PHP, put in the plugins directory of smarty
The contents of block.cacheless. PHP are as follows:
< ? PHP
Function smarty_block_cacheless($param, $content, &$smarty) {
Return the $content;
}
? >
2) write programs and templates
Example program: testcacheless.php
< ? PHP
Include (' Smarty. Class. PHP);
$smarty = new smarty;
$smarty - > Caching = true;
$smarty - > Cache_lifetime = 6;
$smarty - > The display (' cache. The TPL ');
? >
Template used :cache.tpl
Cached :{$smarty.now}< Br>
{cacheless}
Uncached :{$smarty.now}
{/ cacheless}
4. Custom cache
Set cache_handler_func to handle the cache using a custom function
Such as:
$smarty - > Cache_handler_func = "myCache";
Function myCache($action, &$smarty_obj, &$cache_content, $tpl_file=null, $cache_id=null, $compile_id=null){
}
This function is generally based on $action to determine the current cache operation:
The switch ($action) {
Case "read":// reads the cache contents
Case "write":// write to the cache
Case "clear" : / / empty
}
Md5 ($tpl_file.$cache_id.$compile_id) is generally used as the only cache_id
If desired, you can use gzcompress and gzuncompress to compress and uncompress

Related articles: