從維護和代碼組織的角度來看,在PHP5中,爲來自Web服務的XML數據創建/定義對象和類是否有意義?在PHP中創建類或僅使用關聯數組來處理XML數據?
以Twitter's API爲例,我將爲每個API方法(狀態,用戶,direct_messages等)設置一個類。對於statuses/public_timeline
,我想有這樣的事情:
class Statuses {
public $status = array(); // an array of Status objects
public function __construct($url) { // load the xml into the object }
}
class Status {
public $created_at, $id, $text; // and the rest of the attributes follow...
}
$public_timeline = new Statuses('http://twitter.com/statuses/public_timeline.xml');
echo $public_timeline->status[0]->text;
或者是更好的一切轉儲到一個關聯數組,所以項目將這樣的訪問:
// the load_xml function is just something that will dump xml into an array
$public_timeline = load_xml('http://twitter.com/statuses/public_timeline.xml');
echo $public_timeline['statuses']['status'][0]['text'];
首先設計:
- 嚴格遵循面向對象的原則
- 看起來像一種更適合編譯語言的方法
二設計:
- 很多API是否被修改,將需要較少的維護。如果API向XML添加屬性,則需要在第一個設計中更新相應的類。
您能否擴展「在大型應用程序中的必要性」?這將是MVC應用程序中的一個庫,其中數據源是Web服務而不是數據庫。這些模型將會是調用數據庫的庫,所以我認爲添加功能的重用/方法將成爲模型的一部分。 – jimyi 2009-08-26 17:50:11
如果您的應用程序很大(您有很多文件,類,功能,數據等),您想要將這些部分彼此分開以便進行代碼可維護性和代碼重用問題。 – 2009-08-26 22:06:44