-
Notifications
You must be signed in to change notification settings - Fork 1
XmlSerializable
Kacper Donat edited this page Apr 17, 2014
·
2 revisions
You can write your own serialization mechanism for your class by XmlSerializable interface. You have to implement only two methods:
public function toXml(\DOMElement $node, XmlSerializer $serializer);
public static function fromXml(\DOMElement $node, XmlDeserializer $deserializer);Time class:
class Time implements \Kadet\XmlSerializer\XmlSerializable {
public $hours;
public $minutes;
public $seconds;
public function toXml(\DOMElement $node, \Kadet\XmlSerializer\XmlSerializer $serializer)
{
$node->appendChild($node->ownerDocument->createElement(
'seconds',
$this->seconds + $this->minutes * 60 + $this->hours * 3600 // calculate total seconds
));
return $node;
}
public static function fromXml(\DOMElement $node, \Kadet\XmlSerializer\XmlDeserializer $deserializer)
{
// create our object to fill
$time = new Time();
// read value from xml node
$total = $node->getElementsByTagName('seconds')->item(0)->nodeValue;
// calculate specific variables
$time->seconds = $total % 60;
$time->minutes = floor($total / 60) % 60;
$time->hours = floor($total / 3600);
return $time;
}
}
$time = new Time();
$time->hours = 12;
$time->minutes = 15;
$time->seconds = 50;Serialization of $time will result in:
<?xml version="1.0" encoding="utf-8"?>
<Time xmlns:s="urn:kadet:serializer" s:type="Time">
<seconds>44150</seconds>
</Time>And if you unserialize that xml you will get:
object(Time)#8 (3) {
["hours"]=>
float(12)
["minutes"]=>
int(15)
["seconds"]=>
int(50)
}
As you can see serialized and unserialized objects are same, as predicted.