Overloading Tags with PHP functions

From: Date: Tue, 15 Jan 2002 17:34:24 +0000
Subject: Overloading Tags with PHP functions
Groups: php.dev 
Request: Send a blank email to php-dev+get-77151@lists.php.net to get a copy of this message
After quite some experimentation with XSLT as well as several template packages, I have come to the conclusion that XSLT has several drawbacks. For one, it makes simple things like variable replacement in HTML more complicated, but makes complex things like conversion of a HTML table into a pie chart close to impossible. Also, XSLTs Xpath is a kind of database language for hierarchical data stores (DOM trees), with all the drawbacks of a nonrelational and incomplete (no join, no aggregation) query language. And as a functional language it sucks, too (http://www.kuro5hin.org/story/2002/1/15/1562/95011). Finally, I always liked the ability of the Roxen webserver to bind code to tags. So I wrote a proof of concept class Transform in PHP, with does just that: It binds opening and closing functions to XML tags. With a version of TIDY linked into PHP as a library, one could even do this stunt with improperly nested HTML. What is this? Attached you find a class Transform, which contains some very rough proof-of-concept code. This code defines an output buffer to capture the XML generated by the page. That XML must be nested properly, as no attempt on capturing any errors is being made. I then use expat to parse that XML and look for function callbacks named just like the tags that are being processed: If a function called tag_open_h1 exists, then it is being called whenever a H1 tag is being seen. Same goes for closing tags. The opening tags are fed the Transform object and the attribuites of the tag. Closing tags are fed the content of the tag. Also, closing tags have access to a variable level, the nesting level, and to an element and attribute stack, as well as the output of their opening tag. Closing tags may even generate tags which need further processing, that is, you may define <b> to be replaced with <font> and <font> to be replaced with <em> and the result of <b/> will be an <em/>. How can this be used for templates? One could use this to define cold fusion and Roxen like tags such as <gtext>bla</gtext>, which will replace itself with an <img/> tag to an image containing the word "bla". A menu will be inserted where a <menu/> tag is shown and so on. Overloading <html/> or <body/> will define the template for a page. The following code is slow and very ad-hoc. Still, I'd like you to have a look at it and think about it - I'll gather reviews and opinions and probably turn it into C at some later time. Kristian

« previous php.dev (#77151) next »