How to chain methods using a DOMDocument?

Do chaining methods with PHP is easy . But I need something like this,

$xml = $dom->transformToThis('file1.xsl')->transformToThis('file2.xsl')->saveXML(); 

or

 $books = $dom-> transformToThis('file1.xsl')-> transformToThis('file2.xsl')-> getElementsByTagName('book'); 

Is this possible with PHP DOMDocument or DOMNode ?


  class DOMxx extends DOMDocument { public function __construct() { parent::__construct("1.0", "UTF-8"); } function trasformToThis($xslfile) { $xsldom = new DOMDocument('1.0', 'UTF-8'); $xsldom->load($xslfile); $xproc = new XSLTProcessor(); $xproc->importStylesheet($xsldom); $this = $xproc->transformToDoc($this); // ERROR! return $this; } } // class 

$this = X is an invalid construct in PHP, and I don't understand the workaround described here . I can use something like $this->loadXML( $xproc->transformToDoc($this)->saveXML() ); but this is a big overload, and the question is how to do the right thing.

Another (wrong) way to try to implement,

  function trasformToThis($xslfile) { ... same ... return $xproc->transformToDoc($this); // lost trasformToThis() method } 

therefore, in this case, the question arises: "How to transfer to DOMxx?".

0
source share
2 answers

How about something like this:

 class DOMxx { function __construct($version = '1.0', $encoding = 'UTF-8') { $this->document = new DOMDocument($version, $encoding); } function __call($name, $args) { $callback = array($this->document, $name); return call_user_func_array($callback, $args); } function transformToThis($xslfile) { $xsldom = new DOMDocument('1.0', 'UTF-8'); $xsldom->load($xslfile); $xproc = new XSLTProcessor(); $xproc->importStylesheet($xsldom); $this->document = $xproc->transformToDoc($this->document); return $this; } } 

Instead of extending from a DOMDocument you save an internal reference to the DOMDocument object inside your DOMxx class. Most methods are simply routed to this internal object using the __call method. And the transformToThis method simply updates the link with the new document returned from the transformToDoc call.

+2
source

Do you have a specific requirement that transformToThis() must change the original object? I would have thought it would be easier to do something like this:

 function trasform($xslfile) { $xsldom = new DOMDocument('1.0', 'UTF-8'); $xsldom->load($xslfile); $xproc = new XSLTProcessor(); $xproc->importStylesheet($xsldom); $xml = $xproc->transformToXML($this); $newDom = new DOMxx(); $newDom.loadXML($xml); return $newDom; } 

If you really want to change the original object, I suppose this will work too (for this last part of the method):

  $xml = $xproc->transformToXML($this); $this.loadXML($xml); return $this; 
0
source

All Articles