views:

133

answers:

2

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.

A: 

Not sure I understand what are you doing. Probably you should create some class myDOMXPath extends DOMXPath which will return objects of my* classes and use it where it needed.

Zyava
A: 

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));
   }
}
thomasrutter