本文為大家分享了php實現搜索類封裝示例,供大家參考,具體內容如下
<?php /** * SoClass.php * 索引與搜索類 */ class SoClass { private $_xindex; private $_xsearch; private $_project; public function __construct($project){ //載入引導文件 require_once 'lib/XS.php'; //初始化 $xs = new XS($project); $this->_project = $project; $this->_xindex = $xs->index; $this->_xsearch = $xs->search; $this->_xsearch->setCharset('UTF-8'); } public function query($keyWord,$row=20,$jnum=0){ $xs = new XS($this->_project); $xs->search->setFuzzy(); $xs->search->setAutoSynonyms(); $xs->search->setQuery($keyWord); //支持同義詞搜索,默認打開 $xs->search->setLimit($row, $jnum); //設置返回結果最多為 5 條,並跳過前 10 條 $docs = $xs->search->search(); //執行搜索,將搜索結果文檔保存在 $docs 數組中 $count = $xs->search->count(); //獲取搜索結果的匹配總數估算值 if($count){ $data = array(); foreach ($docs as $key=>$doc){ $data[$key]['pid'] = $doc->pid; $data[$key]['nid'] = $doc->nid; $data[$key]['category'] = $doc->category; $data[$key]['url'] = $doc->url; $data[$key]['name'] = $xs->search->highlight(htmlspecialchars($doc->name)); $data[$key]['message'] = $xs->search->highlight(htmlspecialchars($doc->message)); } return array('data'=>$data,'count'=>$count); } return array(); } public function hotWord($num,$type='lastnum'){ return $this->_xsearch->getHotQuery($num,$type); } public function expanded($keyWord){ return $this->_xsearch->getExpandedQuery($keyWord); } public function lastCount(){ return $this->_xsearch->getLastCount(); } public function index($data,$update=0){ // 創建文檔對象 $doc = new XSDocument; $doc->setFields($data); // 添加或更新到索引數據庫中 if(!$update){ $this->_xindex->add($doc); }else{ $this->_xindex->update($doc); } } public function delete($idArray){ //刪除索引(主鍵刪除array('1','2','3')) $this->_xindex->del($idArray); } public function addSynonym($word1,$word2){ $this->_xindex->addSynonym($word1,$word2); } public function clearIndex(){ $this->_xindex->clean(); } } ?>
以上就是本文的全部內容,希望對大家學習php程序設計有所幫助。