Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending DOMDocument and DOMNode: problem with return object

I'm trying to extend the DOMDocument class so as to make XPath selections easier. I wrote this piece of code:

class myDOMDocument extends DOMDocument {

 function selectNodes($xpath){
   $oxpath = new DOMXPath($this);
    return $oxpath->query($xpath);
  }

  function selectSingleNode($xpath){
   return $this->selectNodes($xpath)->item(0);
  }
}

These methods return a DOMNodeList and a DOMNode object, respectively. What I'd like to do now is to implement similar methods to the DOMNode objects. But obviously if I write a class (myDOMNode) that extends DOMNode, I won't be able to use these two extra methods on the nodes returned by myDOMDocument because they're DOMNode (and not myDOMNode) objects.

I'm rather a beginner in object programming, I've tried various ideas but they all lead to a dead-end.

Any hints? Thanks a lot in advance.

like image 812
Nicolas Le Thierry d'Ennequin Avatar asked Oct 15 '22 07:10

Nicolas Le Thierry d'Ennequin


2 Answers

Try using encapsulation instead of inheritance. That is, instead of writing a class that extends the native DOMNode class, write a class stores an instance of DOMNode inside it, and provides only the methods you need.

This allows you to write a constructor that effective turns a DOMNode into a MyNode:

class MyNode {
   function __construct($node) {
      $this->node = $node;
   }

   // (other helpful methods)

}

For your class MyDocument, you output MyNode objects rather than DOMNode objects:

class MyDocument {

   // (other helpful methods)

   function selectSingleNode($xpath) {

      return new MyNode($this->selectNodes($xpath)->item(0));
   }
}
like image 81
thomasrutter Avatar answered Oct 17 '22 10:10

thomasrutter


Use registerNodeClass which will make the document always return nodes as your class instead of the default DOMElement

http://php.net/manual/en/domdocument.registernodeclass.php

like image 41
user2782001 Avatar answered Oct 17 '22 11:10

user2782001