キャッシュ可能なプラグインの出力の制御

Smarty 2.6.0 から、プラグインを登録する際にキャッシュ可能なプラグインを宣言する事が出来ます。 register_block, register_compiler_function, register_function の第3パラメータは $cacheable と呼ばれ、デフォルトは true です。この時、Smarty 2.6.0 以前のプラグインの振る舞いになります。

$cacheable = false であるプラグインが登録された時、プラグインはページがキャッシュから読まれる場合でもページを表示する度に呼ばれます。プラグイン関数は insert 関数に少し似た振る舞いをします。

{insert} とは対照的に、プラグインの属性はデフォルトではキャッシュされません。 キャッシュするためには第4パラメータ $cache_attrs によって宣言します。$cache_attrs はキャッシュされるべき属性の名前を格納した配列であり、プラグイン関数はページがキャッシュから取り出される度に属性はキャッシュに記述されていたものとして値を取得します。

例 13-10. プラグインの出力がキャッシュされるのを防ぐ

<?php
require('Smarty.class.php');
$smarty = new Smarty;
$smarty->caching = true;

function
remaining_seconds($params, &$smarty) {
    
$remain = $params['endtime'] - time();
    if (
$remain >=0)
        return
$remain . " second(s)";
    else
        return
"done";
}

$smarty->register_function('remaining', 'remaining_seconds', false, array('endtime'));

if (!
$smarty->is_cached('index.tpl')) {
    
// データベースから $obj を取り出して割り当てる
    
$smarty->assign_by_ref('obj', $obj);
}

$smarty->display('index.tpl');
?>

index.tpl :

残り時間: {remaining endtime=$obj->endtime}

たとえページがキャッシュされていても $obj の endtime の秒数までは各ページの表示は変更されていきます。 その後のリクエストでページがキャッシュに書かれている時、endtime 属性がキャッシュされたので オブジェクトをデータベースから取り出す必要があるだけです。

例 13-11. テンプレートの一節がキャッシュされるのを防ぐ

index.php:

<?php
require('Smarty.class.php');
$smarty = new Smarty;
$smarty->caching = true;

function
smarty_block_dynamic($param, $content, &$smarty) {
    return
$content;
}
$smarty->register_block('dynamic', 'smarty_block_dynamic', false);

$smarty->display('index.tpl');
?>

index.tpl :

Page created: {"0"|date_format:"%D %H:%M:%S"}

{dynamic}

Now is: {"0"|date_format:"%D %H:%M:%S"}

... 他にも何か ...

{/dynamic}

ページをリロードした時に、両方の日付が異なる点に注意して下さい。一つは"dynamic"であり、もう一つは"static"です。 {dynamic}...{/dynamic} 間に含まれるコンテンツ全てを動的に生成する事ができ、残るコンテンツはキャッシュされない事を確認して下さい。