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.
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));
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With