我不能确定,但你要做的是
smell
,像
Gordon
已经指出了。
不管怎样…你
能够
使用
__call()
根据实际节点(键入/contents/…)在extdomElement对象上公开不同的方法。为此,extdomElement对象可以存储一个根据元素的“类型”实例化的助手对象,然后将方法调用委托给该助手对象。就我个人而言,我不太喜欢它,因为它并不能使文档、测试和调试变得更容易。如果你觉得可行,我可以写一个独立的例子。
这当然需要评论/文档…因为我现在没有时间,所以正在进行工作…
<?php
$doc = new MyDOMDocument('1.0', 'iso-8859-1');
$doc->loadxml('<animals>
<Foo name="fido" />
<Bar name="lucky" />
<Foo name="scratchy" />
<Ham name="flicka" />
<Egg name="donald" />
</animals>');
$xpath = new DOMXPath($doc);
foreach( $xpath->query('//Foo') as $e ) {
echo $e->name(), ': ', $e->foo(), "\n";
}
echo "----\n";
foreach( $xpath->query('//Bar') as $e ) {
echo $e->name(), ': ', $e->bar(), "\n";
}
echo "====\n";
echo $doc->savexml();
class MyDOMElement extends DOMElement {
protected $helper;
public function getHelper() {
// lazy loading and caching the helper object
// since lookup/instantiation can be costly
if ( is_null($this->helper) ) {
$this->helper = $this->resolveHelper();
}
return $this->helper;
}
public function isType($t) {
return $this->getHelper() instanceof $t;
}
public function __call($name, $args) {
$helper = $this->getHelper();
if ( !method_exists($helper, $name) ) {
var_dump($name, $args, $helper);
throw new Exception('yaddayadda');
}
return call_user_func_array( array($this->helper, $name), $args);
}
public function releaseHelper() {
// you might want to consider something like this
// to help php with the circular references
// ...or maybe not, haven't tested the impact circual references have on php's gc
$this->helper = null;
}
protected function resolveHelper() {
// this is hardcored only for brevity's sake
// add any kind of lookup/factory/... you like
$rv = null;
switch( $this->tagName ) {
case 'Foo':
case 'Bar':
$cn = "DOMHelper".$this->tagName;
return new $cn($this);
default:
return new DOMHelper($this);
break;
}
}
}
class MyDOMDocument extends DOMDocument {
public function __construct($version=null,$encoding=null) {
parent::__construct($version,$encoding);
$this->registerNodeClass('DOMElement', 'MyDOMElement');
}
}
class DOMHelper {
protected $node;
public function __construct(DOMNode $node) {
$this->node = $node;
}
public function name() { return $this->node->getAttribute("name"); }
}
class DOMHelperFoo extends DOMHelper {
public function foo() {
echo 'foo';
$this->node->appendChild( $this->node->ownerDocument->createElement('action', 'something'));
}
}
class DOMHelperBar extends DOMHelper {
public function bar() {
echo 'bar';
$this->node->setAttribute('done', '1');
}
}
印刷品
fido: foo
scratchy: foo
----
lucky: bar
====
<?xml version="1.0"?>
<animals>
<Foo name="fido"><action>something</action></Foo>
<Bar name="lucky" done="1"/>
<Foo name="scratchy"><action>something</action></Foo>
<Ham name="flicka"/>
<Egg name="donald"/>
</animals>