用留言功能实现PbootCms文章评论
前言
废话不多说,今天上一个用PbootCms留言板实现文章留言的功能。
操作思路
给留言板添加字段,例如叫:articleid
然后在文章下面加入留言表单。
在表单中增加一个隐藏字段:
<!--用来记录文章的ID-->
<input type="hidden" value="{content:id}" name="articleid">
如果不需要在文章下显示评论,到这里就结束啦。还可以多加几个隐藏字段,记录文章标题,文章URL,方便查看。
那教程肯定不能这么没营养了。
我们使用message标签加载留言列表的时候,会把所有的留言都加载出来,再加上一个判断articleid=={content:id},就实现了评论列表读取。这个方法有个严重的BUG,就是分页会不准确。可能出现1页都没一条评论的情况。
优化方案
那么我们需要对message标签进行一个优化,来更好的实现评论列表效果。
优化后的message标签如下,通过filter属性来过滤出我们所需的留言(评论)
{pboot:message num=10 filter=articleid|{content:id} page=1}
{/pboot:message}
修改文件位置1:/apps/home/controller/ParserController.php,大约在1866行,找到parserMessageLabel方法
为了突出重点,代码仅贴了主要部分,看我的注释@cms88,小朋友请自行整合。
// 解析留言板标签
public function parserMessageLabel($content)
{
$pattern = '/\{pboot:message(\s+[^}]+)?\}([\s\S]*?)\{\/pboot:message\}/';
$pattern2 = '/\[message:([\w]+)(\s+[^]]+)?\]/';
if (preg_match_all($pattern, $content, $matches)) {
$count = count($matches[0]);
for ($i = 0; $i < $count; $i ++) {
// 获取调节参数
$params = $this->parserParam($matches[1][$i]);
$num = $this->config('pagesize');
$page = true;
$start = 1;
$lg = '';
$filter = '';
foreach ($params as $key => $value) {
......
}
// 起始数校验
if (! is_numeric($start) || $start < 1) {
$start = 1;
}
// filter数据筛选 @cms88
$where = array();
if ($filter) {
$filter = explode('|', $filter);
$where = $filter[0] . "='" . escape_string($filter[1]) . "'";
}
// 读取数据 @cms88
if (! $data = $this->model->getMessage(escape_string($num), $page, $start, $lg, $where)) {
$content = str_replace($matches[0][$i], '', $content);
continue;
}
// 匹配到内部标签
if (preg_match_all($pattern2, $matches[2][$i], $matches2)) {
$count2 = count($matches2[0]); // 循环内的内容标签数量
} else {
$count2 = 0;
}
$out_html = '';
$key = 1;
foreach ($data as $value) { // 按查询数据条数循环
......
}
$content = str_replace($matches[0][$i], $out_html, $content);
}
}
return $content;
}
修改位置2:/apps/home/model/ParserModel.php,大约在723行,getMessage方法。
// 获取留言
public function getMessage($num, $page = true, $start = 1, $lg = null, $filter = null) //@cms88 增加filter
{
if ($lg == 'all') {
$where = array();
} elseif ($lg) {
$where = array(
'acode' => $lg
);
} else {
$where = array(
'acode' => get_lg()
);
}
if ($page) {
return parent::table('ay_message')->where("status=1")
->where($where)
->where($filter, 'OR')
->order('id DESC')
->decode(false)
->page(1, $num, $start)
->select();
} else {
return parent::table('ay_message')->where("status=1")
->where($where)
->where($filter, 'OR')
->order('id DESC')
->decode(false)
->limit($start - 1, $num)
->select();
}
}
至此,功能实现。学会的同学点个赞呗。
正文完
评论区