2010-03-07 135 views
2

如何扩展文档对象模型提供的对象?似乎没有办法according to this issue扩展DOMElement对象

class Application_Model_XmlSchema extends DOMElement 
{ 
    const ELEMENT_NAME = 'schema'; 

    /** 
    * @var DOMElement 
    */ 
    private $_schema; 

    /** 
    * @param DOMDocument $document 
    * @return void 
    */ 
    public function __construct(DOMDocument $document) { 
     $this->setSchema($document->getElementsByTagName(self::ELEMENT_NAME)->item(0)); 
    } 

    /** 
    * @param DOMElement $schema 
    * @return void 
    */ 
    public function setSchema(DOMElement $schema){ 
     $this->_schema = $schema; 
    } 

    /** 
    * @return DOMElement 
    */ 
    public function getSchema(){ 
     return $this->_schema; 
    } 

    /** 
    * @param string $name 
    * @param array $arguments 
    * @return mixed 
    */ 
    public function __call($name, $arguments) { 
     if (method_exists($this->_schema, $name)) { 
      return call_user_func_array(
       array($this->_schema, $name), 
       $arguments 
      ); 
     } 
    } 
} 

$version = $this->getRequest()->getParam('version', null); 
$encoding = $this->getRequest()->getParam('encoding', null); 
$source = 'http://www.w3.org/2001/XMLSchema.xsd'; 

$document = new DOMDocument($version, $encoding); 
$document->load($source); 

$xmlSchema = new Application_Model_XmlSchema($document); 
$xmlSchema->getAttribute('version'); 

我得到了一个错误:

Warning: DOMElement::getAttribute(): Couldn't fetch Application_Model_XmlSchema in C:\Nevermind.php on line newvermind

回答

1

由于getAttribute已在DOMElement中定义,因此不会使用您的__call。因此,任何对Application_Model_XmlSchema::getAttribute的呼叫都将通过继承的DOMElement::getAttribute导致您的问题。

如果您需要该功能,快速解决方法是从类定义中除去extends DOMElement,并使用魔术方法将请求路由到DOMElement方法/属性:让您的类充当包装而不是子级。

0

解决方法是:

$xmlSchema->getSchema()->getAttribute('version'); 

不过,我想用 “正常” 的访问方法。