手把手教你做关键词匹配项目(搜索引擎)---- 第十二天

第十二天

起点:

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')


 

posted @ 2014-08-20 13:10  oShine.Q  阅读(1977)  评论(1编辑  收藏  举报