OOP - Extending DOMElement in PHP with registerNodeClass

danger2259

New Member
\[code\]registerNodeClass\[/code\] is great for extending the various DOMNode-based DOM classes in PHP, but I need to go one level deeper.I've created an \[code\]extDOMElement\[/code\] that extends \[code\]DOMElement\[/code\]. This works great with \[code\]registerNodeClass\[/code\], but I would like to have something that works more like this:\[code\]registerNodeClass("DOMElement->nodeName='XYZ'", 'extDOMXYZElement')\[/code\]Consider the following XML document, animals.xml:\[code\]<animals> <dog name="fido" /> <dog name="lucky" /> <cat name="scratchy" /> <horse name="flicka" /></animals>\[/code\]Consider the following code:\[code\]extDomDocument extends DOMDocument { public function processAnimals() { $animals = $this->documentElement->childNodes; foreach($animals as $animal) { $animal->process(); } }}extDOMElement extends DOMElement { public function process() { if ($this->nodeName=='dog'){ $this->bark(); } elseif ($this->nodeName=='cat'){ $this->meow(); } elseif ($this->nodeName=='horse'){ $this->whinny(); } this->setAttribute('processed','true'); } private function bark () { echo "$this->getAttribute('name') the $this->nodeName barks!"; } private function meow() { echo "$this->getAttribute('name') the $this->nodeName meows!"; } private function whinny() { echo "$this->getAttribute('name') the $this->nodeName whinnies!"; }}$doc = new extDOMDocument();$doc->registerNodeClass('DOMElement', 'extDOMElement');$doc->loadXMLFile('animals.xml');$doc->processAnimals();$doc->saveXMLFile('animals_processed_' . Now() . '.xml');\[/code\]Output:fido the dog barks!lucky the dog barks!scratchy the cat meows!flicka the horse whinnies!I don't want to have to put bark(), meow() and whinny() into extDOMElement - I want to put them into extDOMDogElement, extDOMCatElement and extDOMHorseElement, respectively.I've looked at the Decorator and Strategy patterns here, but I'm not exactly sure how to proceed. The current setup works OK, but I'd prefer to have shared properties and methods in \[code\]extDOMElement\[/code\] with separate classes for each ElementName, so that I can separate methods and properties specific to each Element out of the main classes.
 
Back
Top