第十二天
起點:
1. 手把手教你做關鍵詞匹配項目(搜索引擎)---- 第一天
回顧:
11.手把手教你做關鍵詞匹配項目(搜索引擎)---- 第十一天
上回說到,關鍵詞應用需求為:
通過淘寶API取到的寶貝標題以及寶貝屬性,匹配出適合該寶貝的關鍵詞.
初期考慮以下因素:
適合人群的匹配 :男裝 (匹配出來的關鍵詞不能有女) 女裝(匹配出來的關鍵詞不能有男) 情侶裝(男女適用) 童裝(?)
淘寶API取出的寶貝屬性字段:

小帥帥想了很久,總算想出來了一個解決方案,方案如下:
<?php
class SelectorItem {
private $item;
public function __construct($item){
$this->item = $item;
}
public function __get($name){
if(isset($this->item->$name)){
return $this->item->$name;
}
return null;
}
public static function createFromApi($num_iid){
$client = new TopClient();
$client->appkey = 'xx';
$client->secretKey = 'xx';
$req = new ItemGetRequest();
$req->setFields('props_name,property_alias,detail_url,cid,title');
$req->setNumIid($num_iid);
$resp = $client->execute($req);
if(isset($resp->code)){
# error handle
throw new Exception($resp->msg, $resp->code);
}
return new self($resp->item);
}
}
$selectorItem = SelectorItem::createFromApi($_REQUEST["num_iid"]);
Logger::trace($selectorItem->props_name);
$blackCharList = array();
$coreCharList = array();
$matchTitle = $selectorItem->title.$selectorItem->props_name;
if(preg_match('/男裝/', $matchTitle)){
$coreCharList = array(
"男裝"
);
$blackList = array(
"女"
);
}else if(preg_match('/女裝/', $matchTitle)){
$coreCharList = array(
"女裝"
);
$blackList = array(
"男"
);
}else if(preg_match('/情侶裝/', $matchTitle)){
$coreCharList = array(
"情侶裝",
"男裝",
"女裝"
);
}else if(preg_match('/童裝/',$matchTitle)){
$coreCharList = array(
"童裝",
"兒童裝",
"女童裝",
"男童裝"
);
}
$where = array();
foreach($coreCharList as $char){
$where[] = " word LIKE '%$char%'";
}
foreach($blackCharList as $char){
$where[] = " word NOT LIKE '%$char%'";
}
if(count($where)>0){
$sql = "SELECT * FROM keywords WHERE ".implode(' AND ',$where);
Logger::trace($sql);
//search database
}
小帥帥很高興的把代碼拿給於老大時,小帥帥被於老大批了,原因很簡單:
1. 沒有考慮未來變化因素
2. if 太多
小帥帥被批了,心裡很不高興,但還是不得不去請教於老大的高招。
於老大給了一個方向給他。
1. 學習設計模式消除過多的if,以及如何去解耦。
設計模式(Design pattern)是一套被反復使用、多數人知曉的、經過分類編目的、代碼設計經驗的總結。使用設計模式是為了可重用代碼、讓代碼更容易被他人理解、保證代碼可靠性。 毫無疑問,設計模式於己於他人於系統都是多贏的;設計模式使代碼編制真正工程化;設計模式是軟件工程的基石脈絡,如同大廈的結構一樣。[來自百度百科]
小帥帥只好去了解設計模式了。
附:
SelectorItem 裡面的 __get 函數,稱為Magic Methods
如:
$selectorItem->title 其實會調用 __get('title')