Monday, February 15, 2010

PHP Serialize DomDocument

Did you ever tried to serialize a DomDocument Object? Well, you can't!
Unless you use a little trick, taking advantage of __sleep and __wakeup magic methods.

Lately i'm using a lot of Zend_Cache mechanism which is quite awesome and easy to use. Specially the Zend_Cache_Frontend_Class frontend, that enables you to cache the return of methods in a fairly transparent way. I had a method that returns a DomDocument Object, and kept getting error when trying to get it back from MemCache. After some investigation I found that Zend_Cache uses serialize(). This function doesn't work with DomDocument Object and another kind of internals. The solution was to make the serialize/unserialize during the __sleep/__wakeup magic methods.

You need to create a class that extends DomDocument as the following code shows:



<?php
class SerializableDomDocument extends DomDocument {

 private $_xml;


 public function __sleep() {
  $this->_xml = $this->saveXML();
  return array('_xml');
 }

 public function __wakeup() {
  $this->loadXML( $this->_xml );
 }
}
?>


This way, you can use Zend_Cache or keep XML DomDocument Objects in $_SESSION.