Extending DOMDocument and DOMNode: problem with return object

I am trying to extend the DOMDocument class to make XPath easier to select. 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, respectively. Now I would like to implement similar methods for DOMNode objects. But, obviously, if I write a class (myDOMNode) that extends DOMNode, I cannot use these two additional methods on the nodes returned by myDOMDocument, because they are DOMNode objects (not myDOMNode).

I am more likely to be new to programming objects, I have tried different ideas, but they all lead to a dead end.

Any clues? Thank you very much in advance.

+4
source share
3 answers

Try using encapsulation instead of inheritance. That is, instead of writing a class that extends its own DOMNode class, a class record stores an instance of DOMNode in it and provides only those methods that you need.

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

 class MyNode { function __construct($node) { $this->node = $node; } // (other helpful methods) } 

For your MyDocument class, you are outputting MyNode objects, not DOMNode objects:

 class MyDocument { // (other helpful methods) function selectSingleNode($xpath) { return new MyNode($this->selectNodes($xpath)->item(0)); } } 
+2
source

Use registerNodeClass, which will make the document always return nodes as your class, not the default DOMElement

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

+1
source

Not sure I understand what you are doing. You should probably create some class. MyDOMXPath extends DOMXPath, which will return objects of my * classes and use them where necessary.

0
source

Source: https://habr.com/ru/post/1305955/


All Articles