我正在通過應用程序中的一個重構階段幫助構建,並且我從未遇到過類似的情況,所以我不太清楚是否存在一種簡化這種方法。如何構建使用相同API認證密鑰的相似類
情景:我們通過其API將我們的內部數據庫連接到Reverb.com,以更新我們的清單的庫存數量和價格以及將訂單拖到我們的內部數據庫中。混響的API需要每個呼叫的身份驗證令牌。令牌是通過首先發送電子郵件和密碼並在響應中接收令牌創建的。我們有三個班。第一類主要是設置認證令牌。其他兩類分別用於訂單和庫存。我們當前的設置爲每個類實例化單獨的對象。這會創建三個不同的混響調用來創建身份驗證令牌。我正試圖消除這種冗餘。
這裏的第一類(revclass.php):
<?php
namespace rev;
class reverbclass
{
protected $reverbEmail;
protected $reverbPassword;
protected $reverbAuth;
public function __construct(){
//Retrieve email and password from database
$reverbinfo = $this->getReverbAppId();
$this->reverbEmail = $reverbinfo['reverb_email'];
$this->reverbPassword = $reverbinfo['reverb_pass'];
//Send email and password and receive back authentication token
$request = $this->getAuth($this->reverbEmail, $this->reverbPassword);
$reverbInfo = json_decode($request, true);
$this->reverbAuth = $reverbInfo['token'];
}
}
這裏的第二類(revorderclass.php):
<?php
namespace rev;
use rev\reverbclass;
class revorderclass extends reverbclass
{
public function getOrders(){
$url = 'https://reverb.com/api/my/orders/selling/awaiting_shipment.json';
$postString = '';
$headers = array(
"Content-type: application/hal+json",
"X-Auth-Token: $this->reverbAuth"
);
$response = $this->reverbCurl($url, 'GET', $headers, $post_string);
return $response;
}
}
這裏的庫存類(revinventoryclass.php):
<?php
namespace rev;
use rev\reverbclass;
class revinventoryclass extends reverbclass
{
public function getReverbListings($page){
$url = 'https://reverb.com/api/my/listings.json?page=' . $page;
$postString = '';
$headers = array(
"Content-type: application/hal+json",
"X-Auth-Token: $this->reverbAuth"
);
$response = $this->reverbCurl($url, 'GET', $headers, $post_string);
return $response;
}
}
這裏是我實例化類(revclasses.php)的地方:
<?php
//Reverb Classes
include_once 'classes/rev/revclass.php';
include_once 'classes/rev/revorderclass.php';
include_once 'classes/rev/revinventoryclass.php';
//Reverb Class Declarations
$reverb = new \rev\reverbclass();
$revorder = new \rev\revorderclass();
$revinventory = new \rev\revinventoryclass();
而且這裏有一個調用來檢索訂單的例子,然後我們會分析它們:
<?php
require 'rev/revclasses.php';
$request = $revorder->getOrders();
我只包括我認爲代碼是問題的關鍵,從而不會把水攪渾更多。再次,一切正常,但我試圖刪除所有三個類實例化時發生的重複API身份驗證調用,以及使代碼更面向對象。現在它感覺過於程序化。任何提示/更正/批評非常感謝!