搜索服务 - 代码示例

SearchService::sanitizeKeyword() - 关键词过滤
use app\common\service\SearchService; // 过滤搜索关键词 $keyword = SearchService::sanitizeKeyword('化工 产品'); // 去除空格、特殊字符、SQL注入 // 返回: 安全的搜索关键词
SearchService::checkSearchRateLimit() - 搜索限流
// 检查搜索频率限制 $allowed = SearchService::checkSearchRateLimit($ip); // 返回: true=允许搜索, false=超过限制 // 用途: 防止恶意频繁搜索
SearchService::saveSearchHistory() - 保存搜索历史
// 保存搜索记录 SearchService::saveSearchHistory('user123', '化工'); // 参数: $userid=会员ID, $keyword=搜索词 // 清除搜索历史 SearchService::clearSearchHistory('user123');
完整搜索流程
// 1. 过滤关键词 $keyword = SearchService::sanitizeKeyword($input); if (empty($keyword)) { return '请输入搜索词'; } // 2. 检查限流 if (!SearchService::checkSearchRateLimit($ip)) { return '搜索过于频繁'; } // 3. 执行搜索 $results = getTableContent('product', 20, [ 'title' => ['like', "%{$keyword}%"] ], 'id desc'); // 4. 保存历史 SearchService::saveSearchHistory($userid, $keyword);

SearchService 说明

搜索流程

1. sanitizeKeyword() - 过滤关键词

2. checkSearchRateLimit() - 检查限流

3. 执行数据库搜索 (getTableContent)

4. saveSearchHistory() - 保存搜索历史

搜索范围

支持搜索: 产品(product)、新闻(news)、视频(video)等模块

搜索字段: title, content, description

支持LIKE模糊匹配