メンテナンスとコード編成の観点から、PHP5 では、Web サービスからの XML データのオブジェクトとクラスを作成/定義することは理にかなっていますか?
例としてTwitter の APIを使用すると、API メソッド (statuses、users、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'];
最初のデザイン:
- オブジェクト指向の原則に厳密に従う
- コンパイルされた言語により適したアプローチのようです
2 番目の設計:
- API が変更された場合、必要なメンテナンスは大幅に少なくなります。API が XML に属性を追加する場合、最初の設計で対応するクラスを更新する必要があります。