Expat Wrapper and SAX Filters
| From: | Luis Argerich | Date: | Tue, 09 Apr 2002 17:14:31 +0000 |
| Subject: | Expat Wrapper and SAX Filters | ||
| Groups: | php.pear.dev | ||
| Request: | Send a blank email to pear-dev+get-5284@lists.php.net to get a copy of this message | ||
After taking a look at your Parser class wrapping the Expat parser I wanted
to share and idea with you.
IMHO the SAX wrapper class should allow the user to set a "listener" object,
an object where SAX events are passed,
the SAX wrapper should implement all the SAX handlers and only do a
$this->listener->nameOfHandler(params) inside.
This way we can program SAX filters that receive SAX events and produce more
SAX events or some result, chaining
filters allow to build complex SAX transformations/modifications or other
operations over XML documents.
For example take a look at this abstract classes:
class AbstractSAXParser {
var $listener;
function AbstractSAXParser() {}
function parserSetoption($opt,$val) {}
function setListener($obj) {
$this->listener=$obj;
}
function startElementHandler($parser,$name,$attribs) {
$this->listener->startElementHandler($name,$attribs);
}
function endElementHandler($parser,$name) {
$this->listener->endElementHandler($name);
}
function characterDataHandler($parser,$data) {
$this->listener->characterDataHandler($data);
}
function parse() {}
}
class AbstractFilter {
var $listener;
function setListener($obj) {
$this->listener=$obj;
}
function startElementHandler($name,$attribs) {}
function endElementHandler($name) {}
function characterDataHandler($data) {}
}
The abstract SAX parser wraps a SAX parser, we can make a derivative class
for Expat or we can also derivate the AbstractClass to a class
that parses non-xml data generating SAX events and thus allowing to convert
non-xml data to XML.
The Filter is the class that receives SAX events and in the handlers perform
some operations and may propagate the events to a next listener,
a final Filter that outputs XML for example just intercepts the events but
don't propagate them.
Example:
$parser=new ExpatParser($xmlfilename); // ExpatParser extends
AbstractSAXPaser
$filter=new Filter(); // Some filter
$parser->setListener($filter);
$parser->parse();
We can for example chain filters to transform a document using several minor
"modular" transformations or modify a document using a filter
that adds or remove elements (several elements can be added or removed if we
queue the modifications in the filter before parsing)
This leads to several advantages since complex transformations/modifications
can be performed reading the XML file just once and at
SAX speed and cosuming very few resources. Results can also be streammed
since SAX allows streaming the result as it is generated.
I believe that PEAR is the place where the "standard" AbstractSAXParser and
Filter classes can be defined standarizing the way to
write SAX filters with PHP.
Let me know what you think about this.