From a maintenance and code organization standpoint, in PHP5, does it make sense to create/define objects and classes for XML data coming from a web service?
Using Twitter's API as an example, I would have a class for each API method (statuses, users, direct_messages, etc). For statuses/public_timeline
, I would have something like this:
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;
Or is it better to dump everything into an associative array, so items would be accessed like this:
// 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'];
First design:
- Strictly following object-oriented principles
- Seems like an approach better suited for compiled languages
Second design:
- A lot less maintenance would be needed if the API is modified. If the API adds an attribute to the XML, the corresponding class would need to be updated in the first design.