SitePoint Sponsor |
|
User Tag List
Results 1 to 1 of 1
Thread: Overloading SimpleXML
-
Feb 26, 2006, 13:25 #1
Overloading SimpleXML
Is it possible to overload SimpleXML? I know you can extend SimpleXMLElement and use that as your node class, but it does not seem to be overloadable.
I am trying to autotype certain keywords. For example yes, no, true, false, etc, to boolean true and boolean false. Otherwise, we'd have to change all existing program code from checking for true/false on certain items to a specific string, which IMO makes the code too brittle and makes it much more difficult to change formats. Right now most files are INI style, but for various reasons we're changing some to XML, so they need to translate pretty much the same to the application. We're using a factory right now with our INI style files that just translates them to basic data objects, i.e, $obj->Section->Parameter, (with autotyping). So then since SimpleXML allows this same style access ($xml->node->node, etc) it makes a perfect candidate for us.
Anyways, I've not had any luck with overloading SimpleXML to allow autotyping. All I've been able to come up with so far is the following, which extends SimpleXML and does work, but apparently SimpleXML elements cannot be boolean, as they are translated to an empty string and a 1, which is ok since normal condition checks (==, !=) will work; however strict checks won't (===, !==), but I don't think that will be a problem.
PHP Code:class AutoTypeSimpleXMLElement extends SimpleXMLElement {
/**
* attempt to auto type certain keywords as boolean
*/
public function autoType() {
foreach ($this->children() as $key => $value) {
$check = $this->checkAutoType($value);
if ($check !== -1) {
$this->$key = $check;
}
$this->$key->autoType();
}
}
protected function checkAutoType($value) {
if (preg_match('/^(true|false|1|0|on|off|yes|no|y|n)$/i', $value)) {
return $this->toBoolean($value);
}
return -1;
}
protected function toBoolean($value) {
if (preg_match('/^(true|1|on|yes|y)$/i', $value)) {
return true;
}
return false;
}
}
function autotype_simplexml_load_string($string) {
$xml = simplexml_load_string($string, 'AutoTypeSimpleXMLElement');
$xml->autoType();
return $xml;
}
function autotype_simplexml_load_file($file) {
$xml = simplexml_load_file($file, 'AutoTypeSimpleXMLElement');
$xml->autoType();
return $xml;
}
So anyways has anyone had any luck overloading SimpleXMLElement?
Bookmarks