给OneThink的TagLib自定义标签添加数据缓存功能

以ThinkPHP/Library/OT/TagLib/Article.class.php为例,添加缓存功能。

原始的_list()对象是这样的:

public function _list($tag, $content){
	$name   = $tag['name'];
	$cate   = $tag['category'];
	$child  = empty($tag['child']) ? 'false' : $tag['child'];
	$row    = empty($tag['row'])   ? '10' : $tag['row'];
	$field  = empty($tag['field']) ? 'true' : $tag['field'];

	$parse  = '<?php ';
	$parse .= '$category=D(\'Category\')->getChildrenId('.$cate.',true);';
	$parse .= '$__LIST__ = D(\'Document\')->page(!empty($_GET["p"])?$_GET["p"]:1,'.$row.')->lists(';
	$parse .= '$category, \'`level` DESC,`id` DESC\', 1,';
	$parse .= $field . ');';
	$parse .= ' ?>';
	$parse .= '<volist name="__LIST__" id="'. $name .'">';
	$parse .= $content;
	$parse .= '</volist>';
	return $parse;
}

在模板中调用的方法为:

<article:list name="v" category="0">
$content
</article:list>

变量$tag中存储的就是在模板中调用时填写的属性值。


那么,为了实现在模板中调用时增加一个cache属性即可实现缓存功能,如:

<article:list name="v" category="0" cache="3600">
$content
</article:list>

需要在进行数据库读取时设置cache(),修改之后的_list()如下所示:

public function _list($tag, $content){
	$name   = $tag['name'];
	$cate   = $tag['category'];
	$child  = empty($tag['child']) ? 'false' : $tag['child'];
	$order    = empty($tag['order']) ? '`level` DESC,`id` DESC' : $tag['order'];
	$row    = empty($tag['row'])   ? '10' : $tag['row'];
	$cache  = empty($tag['cache']) ? false : $tag['cache'];
	$field  = empty($tag['field']) ? 'true' : $tag['field'];

	$tag = array_merge($tag, array('tag' => 'article', 'action' => 'list')); //注明标签类型
	$cacheID = to_guid_string($tag);

	$parse  = '<?php ';
	$parse .= '$category=D(\'Category\')->getChildrenId('.$cate.',true);';
	$parse .= '$__LIST__ = D(\'Document\')->';
	if($cache !== false && is_numeric($cache)){
		$parse .= 'cache(\''.$cacheID.'\','.$cache.')->';
	}
	$parse .= 'page(!empty($_GET["p"])?$_GET["p"]:1,'.$row.')->lists(';
	$parse .= '$category, '.$order.', 1,';
	$parse .= $field . ');';
	$parse .= ' ?>';
	$parse .= '<volist name="__LIST__" id="'. $name .'">';
	$parse .= $content;
	$parse .= '</volist>';
	return $parse;
}

首先会判断$tag['cache']的值,如果为数字则在执行数据库读时进行cache,键名为根据查询条件生成的唯一id:

$cacheID = to_guid_string($tag);

这样,就能方便地在模板中使用缓存调用功能了~

你可能感兴趣的:(缓存,onethink)