首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

關鍵詞匹配項目實戰(九):Curl 封裝與代碼重構初探

     編輯:PHP 相關知識

關鍵詞匹配項目實戰(九):Curl 封裝與代碼重構初探

系列第九天。小帥帥接手於老大的 TopClient 類,發現其核心請求方法基於 Curl,嘗試用自研的 ExtendedCurl 替換底層實現,開啟了重構之路。

重構前:原生 Curl 實現

TopClient 內部直接操作 Curl 句柄,代碼分散、難以複用。

重構後:注入 ExtendedCurl

<?php
class TopClient {
    // ...
    protected function curl($url, $postFields = null) {
        $options = [
            CURLOPT_FAILONERROR      => false,
            CURLOPT_RETURNTRANSFER   => true,
            CURLOPT_CONNECTTIMEOUT   => 15,
            CURLOPT_TIMEOUT          => 300,
            CURLOPT_FOLLOWLOCATION   => 1,
        ];
        $curl = new ExtendedCurl($options);
        $reponse = $curl->post($url, $postFields);
        
        if ($curl->hasError()) {
            throw new Exception($curl->getError(), 0);
        } else {
            if (200 !== $curl->getHttpCode()) {
                throw new Exception($reponse, $curl->getHttpCode());
            }
        }
        return $reponse;
    }
    // ...
}

調用示例

$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
} else {
    // success handle
}

加入淘寶開放平台

官方指引:https://open.taobao.com

導師評審與新任務

於老大肯定重構成果,並提出新要求:將 TopClient 中的 logCommunicationError 日誌記錄邏輯提煉為通用的 Logger 組件。小帥帥領命開展 Logger 設計。

階段性成長

從「調用現成庫」到「封裝底層網絡層」,再到「提煉通用組件」,小帥帥的代碼組織能力與抽象思維顯著提升。下一期將展示 Logger 組件的設計演進。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved