Smarty緩衝處理函數

Cache Handler Function

緩衝處理函數

作爲一個可選擇使用的默認基於文本的緩衝機制,你可以定製或者自定義緩衝處理函數來進行讀、寫、清除緩衝文件。

如果要在應用程序下建立一個函數,SMARTY將會使用一個緩衝處理。設置這個函數名爲 $cache handler func 中類變量名。Smarty將使用這個函數來處理緩衝數據。第一個參數不管是‘讀’,‘寫’,‘清除’,都是動態的。第二個參數是 Smarty 對象。第三個參數是緩衝的內容。在進行寫操作之前,Smarty 傳遞這些緩衝內容給這些參量。在進行讀操作之前,Smarty預處理那些緩衝數據相關或者封裝好了的函數。在進行清除操作之前,從他沒有使用起,就傳遞一個虛擬變量。第四個參數是模板文件名(需要讀和寫的文件),第五個函數是緩衝ID(額外選項),然後第六個參數是編譯的ID(額外選項)。

Note: The last parameter ($exp_time) was added in Smarty-2.6.0.

注意:最新的參數名 ($exp_time) 在Smarty-2.6.0中才加入的。

cache\_handler\_func = 'mysql\_cache\_handler'; $smarty->display('index.tpl'); mysql database is expected in this format: create database SMARTY\_CACHE; create table CACHE\_PAGES( CacheID char(32) PRIMARY KEY, CacheContents MEDIUMTEXT NOT NULL ); \*/ function mysql\_cache\_handler($action, &$smarty\_obj, &$cache\_content, $tpl\_file=null, $cache\_id=null, $compile\_id=null, $exp\_time=null) { // set db host, user and pass here $db\_host = 'localhost'; $db\_user = 'myuser'; $db\_pass = 'mypass'; $db\_name = 'SMARTY\_CACHE'; $use\_gzip = false; // create unique cache id $CacheID = md5($tpl\_file.$cache\_id.$compile\_id); if(! $link = mysql\_pconnect($db\_host, $db\_user, $db\_pass)) { $smarty\_obj->\_trigger\_error\_msg("cache\_handler: could not connect to database"); return false; } mysql\_select\_db($db\_name); switch ($action) { case 'read': // save cache to database $results = mysql\_query("select CacheContents from CACHE\_PAGES where CacheID='$CacheID'"); if(!$results) { $smarty\_obj->\_trigger\_error\_msg("cache\_handler: query failed."); } $row = mysql\_fetch\_array($results,MYSQL\_ASSOC); if($use\_gzip && function\_exists("gzuncompress")) { $cache\_contents = gzuncompress($row\["CacheContents"\]); } else { $cache\_contents = $row\["CacheContents"\]; } $return = $results; break; case 'write': // save cache to database if($use\_gzip && function\_exists("gzcompress")) { // compress the contents for storage efficiency $contents = gzcompress($cache\_content); } else { $contents = $cache\_content; } $results = mysql\_query("replace into CACHE\_PAGES values( '$CacheID', '".addslashes($contents)."') "); if(!$results) { $smarty\_obj->\_trigger\_error\_msg("cache\_handler: query failed."); } $return = $results; break; case 'clear': // clear cache info if(empty($cache\_id) && empty($compile\_id) && empty($tpl\_file)) { // clear them all $results = mysql\_query("delete from CACHE\_PAGES"); } else { $results = mysql\_query("delete from CACHE\_PAGES where CacheID='$CacheID'"); } if(!$results) { $smarty\_obj->\_trigger\_error\_msg("cache\_handler: query failed."); } $return = $results; break; default: // error, unknown action $smarty\_obj->\_trigger\_error\_msg("cache\_handler: unknown action "$action""); $return = false; break; } mysql\_close($link); return $return; } ?>