For the past few days I’ve been toying with a set of classes in PHP that is basically a fluent interface for generating HTML. A basic usage example is:
echo p(b('This'), ' is a ', i('test'))->addClass('foo')->html();
echo new Paragraph( new Bold('This'), ' is a ', new Italic('test'))->addClass('foo')->html();
echo new Paragraph()->append(new Bold('This')) ->append(' is a ') ->append(new Italic('test') ->addClass('foo') ->html();
<p class="foo"><b>This</b> is a <i>test</i></p>
My goals in doing this were to:
- Create a terse fluent interface for gnerating HTML;
- Create valid HTML. This code currently implements the HTML 4.01 Transitional standard so it'll generate an error if you try and append a <p> element to an <object> element, for example;
- Correctly handle HTML escaping implicitly; and
- Provide a level of jQuery like manipulation functionality.
I did this largely to see how it would turn out. Basically for my own curiosity. I don't even know if I'll be using this with what I'm working on but just in case I have to ask: is this something others might be interested in?
I haven't seen anything like it but that doesn't mean it hasn't already been done. If there is interest in it, even if its just idle curiosity, I'll clean it up and open source it.