系列第九天。小帥帥接手於老大的 TopClient 類,發現其核心請求方法基於 Curl,嘗試用自研的 ExtendedCurl 替換底層實現,開啟了重構之路。
TopClient 內部直接操作 Curl 句柄,代碼分散、難以複用。
<?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
}
於老大肯定重構成果,並提出新要求:將 TopClient 中的 logCommunicationError 日誌記錄邏輯提煉為通用的 Logger 組件。小帥帥領命開展 Logger 設計。
從「調用現成庫」到「封裝底層網絡層」,再到「提煉通用組件」,小帥帥的代碼組織能力與抽象思維顯著提升。下一期將展示 Logger 組件的設計演進。