Page 1 of 2

Your own template-engines...

Posted: Thu Aug 14, 2003 7:25 am
by JAM
This might just have happened to me, but I think I'm working on my 15th template engine (and I guess that some of them are the same) and I'm getting tired that I cannot settle down with 'a final solution'.

One day, Im using a class, reading files, replacing a special tag within those with something i fetch using call_user_function.
Next day I use function_header/footer/...() functions only.
Next day again, I'm combining everything...

We all think differently, but I still would like some of your ideas of what you have done regarding the subject. Preferably stating pro's/con's as I want to learn from others experience.

XSLT

Posted: Thu Aug 14, 2003 9:15 am
by greenhorn666
I've settled down to this solution:
Object => XML => XSLT => HTML

Meaning I code everything OO, I put all the objects I need in a "response object" that then transform all these objects (and what's in the SESSION automatically) in XML thru a little function that takes one argument: an xsl file.
Using the sablotron extension, it then transform this XML using the XSL in HTML.

Pros:
This has one major advantage over all other solutions I've seen so far:
MVC that is!
You clearly can draw a line between you model, you view and your controller! Which results in manageable source!
You can easely add a language (translate the XSL), another platform (WML use another XSL); change access rights by modifying the controller (which is a small php scripts that handles the objects, in order to instanciate them and/or put them in the right state); or add/modify functionnality (modify the class) without any other drawbacks (almost always, if you model your classes right ;) )

Cons:
You'll have to wait till php5 is out before I make this framework public ;)
A bit heavy maybe, but I could never experience drawbacks due to this...
It's even faster in the end, cause I think you end up coding cleaner than messy like it always end in huge projects with php, html and sql all messed up in one huge file.
And a bit longer to get something (which again is a pro in some way, cause you almost always end up with a clean code following the MVC paradigm).

I'm tweaking on some aspect of the solution right now, that cry for php5 OO functionnality!
Just tell me if that could interest you...

Object => XML => XSLT => HTML

Posted: Mon Aug 25, 2003 3:29 am
by Bitmaster
That seems like a nice, clean solution. I'm considering it too, so I would like to hear more about it.
But there's only one problem: my web designers dont understand XML / XSL. I was wondering if there's anything like a visual interactive XSL designer for non-programmers or do you write the transforms by hand ?

Posted: Mon Aug 25, 2003 7:00 am
by greenhorn666
As for now I write the stylesheets by hand.
But I used to do so for HTML also...
I am about to hire my first web designer, but am asking for XSL (not really XML, since I already ask for XHTML, the rules are basically enough for XSL)...
Time they get some real work done too, come on Dreamweaver is no solution, now is it? ;)

Wow

Posted: Mon Aug 25, 2003 3:09 pm
by rms
This sounds very interesting to me too.
An example of a .php-, .xml- and .xsl-file would be greatly appreciated. I haven't worked alot with XML/XSL. :?

Re: XSLT

Posted: Mon Aug 25, 2003 7:58 pm
by JAM
greenhorn666 wrote:A bit heavy maybe, but I could never experience drawbacks due to this...
All above sound interesting, as I got some hand in on all of it, but (as quoted) it is heavy, for me. Having used it, and using it is two different things, but we all are learners. :wink:

If anyone else are making sites with the "same'ol'same" solution each time, please comment on what type youre stuck with. Personally at writing point I'm trying out storing css's, and layout-blocks in a database (imho feels odd but I'm messing around).

greenhorn666:
Considered writing an article about your solution/ideas? Personally, it would be interesting.

Posted: Mon Aug 25, 2003 9:19 pm
by McGruff
Recent thread on template engines:

viewtopic.php?t=10077

Posted: Fri Aug 29, 2003 4:01 pm
by juesch
I've been using SmartTemplate for much of my recent work. It's leaner and faster than SMARTY and draws a better line on how much logic should go into a template.

I've written a few extensions myself, was pretty easy. But after doing a few I realized that it is better to manipulate the data in the script for complex output and keep the template as simple as possible. With very few exceptions I'm not a big supporter of logic and functions in templates at all.

You need Blocks. You may benefit from IF, ELSEIF, ELSE.

SmartTemplate has a few issues and the auther doesn't seem to have too much time to dedicate to fix them at this time or add some functionality.

Once PHP5 goes solid, I'll probably attempt to move to XML/XLST transforms. I really think that the ultimate solution.

Juergen
[/url]

Re: XSLT

Posted: Fri Aug 29, 2003 4:21 pm
by greenhorn666
JAM wrote: greenhorn666:
Considered writing an article about your solution/ideas? Personally, it would be interesting.
Well I'm no good writer and have way to much things to do, I would never get the time to get this done! ( My daughter just got born yesterday :) )

But as I said I will release the whole framework once php5 is out and I get to fine tune some stuff (like private members not being "transformed" to XML ie, for now I tweaked my own php objects -> XML engine to only care about vars not starting with an underscore (_) which I think is are the kind of way too messy hack for a release!)

I'll release with a small demo app that I'll code using this (like an hello world or something à la example from the Sam's kick start struts book).

But if you are interested I could put up some "pre-" release (I already thought of that, due to some requested mods I could actually do in order to satisfy the most, before releasing the actual framework... Since I only used and modified the whole for my purposes). You check the thing out, if you think this could really be of interest for people, you write the article! (and why not the docs ;) )
JAM wrote: but (as quoted) it is heavy, for me.
Well there comes another interesting point, the main webapp for which I coded that is doing quite a lot of cobranding with main IP portals here in Belgium and they all work in XML. Hence I believe that soon or later you'll need to get your data in an XML stream (easely XSLTranformable to a much ligther XML stream for a particular purpose; or even to use WML, PDFs or whatever format...)

I don't really think the sablotron extension really "heavies" the stuff, but actually the php parser that transforms my objects into XML streams (since I get to parse quite a few objects in some cases)

Re: XSLT

Posted: Fri Aug 29, 2003 6:40 pm
by JAM
greenhorn666 wrote: Well I'm no good writer and have way to much things to do, I would never get the time to get this done! ( My daughter just got born yesterday )
I guess a big congratulations is in order! Ylack of free-time will take another 7-8 years in best case to change then. :D

If you want, try to remember me when you decide to go 'public' with the little project of yours. I find it really very, very interesting, and as I'm rather new to the area it would be like a good book going thru the work.

If I would understand it well enough, I would doc'late it... At least, for personal use (I do that with most code I save that I borrowing from other applications), but that might be good enough.

Posted: Mon Sep 15, 2003 4:06 pm
by NoReason
forgive my ignorance, but I dont see any reason to have a document template as XML.. Now I am fairly new to XML and have done very limited reporting with it.. No transformations or DTD/Schema validation.

BUT, I have done plenty of PHP and template design using various methods; includes , parsing, etc..

But in all of this did I never once think of using xml as a template system.
Dont get me wrong, it may be that I do not understand the full scope, but if the end result is still going to be HTML.. wh not just do it in html.

My main project is a tracking system for people/items/resources etc.. That requires grainular permission, form validation (java script). And at times I am required to break te mold so to speak, now if I was working with a true template system i would never be able to squeeze the functionality that is required to make the application work.. Now as i stated above it my be ignorance.. But I am making the best descisions without the knowedge I have at the moment... I am learning new things each day so its all good there.. but at the same time I can be redo my client interface every week becuase I foudn a differant way of doing things..

as it is i am dabbling in; php,java script, DHTML, and MSSQL in order to get the full potential out of the system.

But I would LOVE to have a set of stanards that I couls use to accomplish my goals without having to "break the mold" of my methodology.. note methodology, not template at this time..

some of the issues i have come accross::
1) need for specific form validation - solved with onSubmit java-script
2) need to track access to specific elements/tool bars/ and functions
- solved using user class to query and store Access Security Lists, the front end using if( $_SESSION['data']->GetAccess('element') ) to determain access..
3) Generic Navigation without $_GET variables - solved using <a href value='INTEGER' onClick='JavaScript to Post hidden form'>LINK</a>
which would force a reload of the wrapper page with the new location..
(some problem with this in that document.form.submit() can not pass named variables without a form to post)


Those are just some of the issues..
So to some up .. how could an XML template(framework?) help my project?

Or am i just barking up the wrong (pear)tree.....

Posted: Mon Sep 15, 2003 6:00 pm
by greenhorn666
Just to make sure we talk about the same problem/solution here:

The framework I discribed above is using html, xhtml actually, extended with xsl tags if you want.
My point is to clearly seperate Model / View / Controller (Model 2, MVC paradigm).

To illustrate this take a look at this:

Code: Select all

$greeter = new Greeter("NoReason");
$HttpResponse->add($greeter);
$HttpResponse->xsltr("hello.xsl");
This would be our controller, let's call this file hello.html.
As you see it creates a new Greeter object, our model (not really, but for the example), that simply could look like this, say greeter.php:

Code: Select all

class Greeter {
    var $name, $ts, $timestamp;

    function Greeter($name) {
        $this->name = $name;
        $this->ts = time();
        $this->timestamp = strftime("%x %X", $this->ts);
    }
}
And adds it to our response, then call a xslt(ransformation) on this response using the xsl template hello.xsl, our view, that could look this:

Code: Select all

&lt;?xml version="1.0" encoding="iso-8859-1"?&gt;
&lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;

    &lt;xsl:output method="xhtml" encoding="iso-8859-1" /&gt;
    &lt;xsl:template match="/"&gt;
        &lt;xsl:apply-templates /&gt;
    &lt;/xsl:template&gt;

    &lt;xsl:template match="response"&gt;
        &lt;html&gt;
        &lt;head&gt;&lt;title&gt;Greater example&lt;/title&gt;&lt;/head&gt;
        &lt;body&gt;
            &lt;h3&gt;On &lt;xsl:value-of select="greeter/timestamp" /&gt;, you said hello to &lt;a&gt;&lt;xsl:attribute name="href"&gt;/user/view?login=&lt;xsl:value-of select="greeter/name" /&gt;&lt;/xsl:attribute&gt;&lt;xsl:value-of select="greeter/login" /&gt;&lt;/a&gt;&lt;/h3&gt;
        &lt;/body&gt;
        &lt;/html&gt;
    &lt;/xsl:template&gt;
&lt;/xsl:stylesheet&gt;
So as you can see you don't really solve it with xml, your data get's represented in XML (that's what happens in the HttpResponse object) and this XML stream representation of the objects you put in your response gets transformed using a XSL template (containing XSL and HTML tags) into your final HTML document that would look like this:

Code: Select all

&lt;html&gt;
        &lt;head&gt;&lt;title&gt;Greeter example&lt;/title&gt;&lt;/head&gt;
        &lt;body&gt;
            &lt;h3&gt;On Friday, November 1 2003 12:04am, you said hello to &lt;a href="/user/view?login=NoReason"&gt;NoReason&lt;/a&gt;&lt;/h3&gt;
        &lt;/body&gt;
        &lt;/html&gt;
This example is fairly simple, it all ties together a bit differently in the whole framework.

So, now that I think we speak about the same thing, I'm open to your criticism, suggestions,...

You can do whatever is needed with that solution, including adding JS and whatever. Sometimes its easier to prepare the data for its end purpose (as I did with $ts and $timestamp); but XSL has basic logic and formatting for your needs :

Code: Select all

&lt;xsl:if test="bool"&gt;&lt;/xsl:if&gt;

&lt;xsl:choose&gt;
    &lt;xsl:when test="bool"&gt;&lt;/xsl:when&gt;
    &lt;xsl:when test="bool"&gt;&lt;/xsl:when&gt;
    &lt;xsl:otherwise&gt;&lt;/xsl:otherwise&gt;
&lt;/xsl:choose&gt;

...
And combined with Xpath you get wherever you want...
I think http://www.w3schools.com has more on those topics

Does that lights it up a bit?

Posted: Mon Sep 15, 2003 6:15 pm
by JAM
Im envious, greenhorn666 ;)
I'd give my neighbours left leg for knowing more about this (I can read around the lines, but not actually write it). Think I need more time behind the desk reading up on things...

There are to many standards out there to learn. It was fun when you had HTML 1 you needed to know, but these days its more annoying.

Posted: Mon Sep 15, 2003 6:41 pm
by NoReason
Ok .. That clarifies it a bit, in that you can have conditional statements in your response object.. that would make consolidating the final document alot easier, as well you would not have your php code "cluttering" up the rest of the page :P

But here is my current methodology that I am using is as follows;

Index Page;

The index page loads stores the current page you are on, using $_SESSION variables.

when a client first loads the page the new User Class object is empty there for Current_Document defaults to the loginDocument.

The wrapper (index page) has all the basic elements that comprise the application, IE: default links (functions) header and footer.. etc.
The content page loads in what ever "module" they are currently browsing.

This is all done by post variables, posting to a proccessing document that then redirects back to the index page, which in turn loads in the Current_Document from the user class and displays the new location or the same one they were at.. with a confirmation message or error report.

Each element on the page (including navigation and module access) has a small if() statement that checks the users access security to determain 1) do they access to it, 2) can they even see it, 3) the level of access to an element IE: a combo box and what options are available.

Those the basics.. there is of course dhtml for added flashy shizz and javascript form validation, etc.. buts mostly error prevention and cosmetics.

So .. with that in mind, using your framework.. could my application work/ be ported over?

edit::
I suppose I should also add that I am doing reports that require iteration thru a query object, dynamic combo box creation.. And that lovely stuff.

Posted: Tue Sep 16, 2003 2:49 am
by greenhorn666
Well, I'm not quite sure I get the whole idea, but:
  • - The content of the session is, if not configured otherwise, included in the XML response document, so that ie. you can access your user information from a template. Having <xsl:if test="/response/session/registereUser"> being true if a registeredUser object is inside our session.
    - What ever is in the SESSION that represent the page the user is trying to view is hence also accessible.
    - Verifying that the user can view the resource is also doable with <xsl:if test="/response/session/registeredUser/level > /response/session/page/level">
But, except for point 1, this breaks the whole framework's idea!
When I said
This example is fairly simple, it all ties together a bit differently in the whole framework.
here's what I meant and how it actually happens:

Code: Select all

&lt;?xml version="1.0" encoding="iso-8859-1"?&gt;
&lt;xsl:stylesheet version="1.0" 
		xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
		
	&lt;xsl:import href="layout/layout.xsl" /&gt;

	&lt;xsl:output method="xhtml" encoding="iso-8859-1" indent="yes" 
		omit-xml-declaration="yes" /&gt;
	
	&lt;xsl:template match="/"&gt;
		&lt;xsl:call-template name="makeLayout" /&gt;
	&lt;/xsl:template&gt;

	&lt;xsl:template match="response"&gt;
&lt;!-- Actual transformation for your page happens here --&gt;
	&lt;/xsl:template&gt;
&lt;/xsl:stylesheet&gt;
So let me explain what happens here:

When you <xsl:import href="layout/layout.xsl"> you actually import your page's layout (menu's may they be conditional or not, but you code it only once). This file, in many cases, contains one simple <table> with 3 rows, the second one having 3 cols, so that you get the basic top, bottom, left, right and main section of your website's layout. The top, left, right and bottom in turn <xsl:import ..> the content for these parts, while the main part contains the, in the above code, missing, <xsl:apply-templates />.
The templates that you want to be applied, you have to define them in the actual file you are editing, like the above code, let's say user/prefs.xsl which contains the form for user preference management.
First advantage, I, ihmo, see here, is that your layout and page are clearly seperated and that way easier maintainable.

Now to form validation:

the following code is a part of what would replace the <!-- Actu... here --> in the above example:

Code: Select all

&lt;table&gt;
&lt;form action="prefs?mod" method="post"&gt;
&lt;xsl:if test="errors"&gt;
&lt;tr&gt;
&lt;td colspan="3"&gt;&lt;b style="color:red"&gt;You didn't fill out the form correctly&lt;/b&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/xsl:if&gt;
&lt;tr&gt;
    &lt;td&gt; Name:&lt;/td&gt;
    &lt;td&gt;&lt;input type="text" name="data&#1111;name]"&gt;
        &lt;xsl:attribute name="value"&gt;&lt;xsl:value-of select="prefs/name" /&gt;&lt;/xsl:attribute&gt;&lt;/input&gt;&lt;/td&gt;
    &lt;td&gt;&lt;xsl:if test="errors/name"&gt;
        &lt;b style="color: red"&gt;&lt;xsl:value-of select="errors/name" /&gt;&lt;/b&gt;
    &lt;/xsl:if&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;!-- snip --&gt;
&lt;/form&gt;
&lt;/table&gt;
As you can see, only the form and it's validation result are showed here (showed! this our view, no logic here; while you could add JS to ease with Client-Side validation).
The validation itself is done in our object prefsForm that get populated by $data[] and the auth requirement is done in the controller, /user/prefs. I use rewrite Rule to get nicer URL, like /user/prefs?mod gets rewritten by apache to /user/prefs.html?action=mod...

So our prefs.html would for instance have an include("auth.inc"); that would be some authentication verification, let say a simple:

Code: Select all

if(!isset($_SESSION["registeredUser"]))
    HttpResponse->redirect("/user/login");
the redirect method of our HttpResponse object is some nice headers being sent to the client, temp moved and location, and then exits;

The controller, in our mod case, simply:

Code: Select all

require("auth.inc");
$prefs = new PrefsForm();
if(isset($_POST["data"])) {
    $prefs->setData($_POST["data"]);
    if($prefs->validate())
        $_SESSION["registeredUser"]->updatePrefs($prefs);
} else 
    $prefs->setData($_SESSION["registeredUser"]->getPrefsData());
    $HttpResponse->add($prefs);
    $HttpResponse->xsltr("user/prefs.xsl");
So this would be a bit more complex example. I haven't talked about the PrefsForm() class that extends a frameworks' own HtmlForm class that implements utilities method for populating, validate and such our forms

But that way you have a clean separation between Model, View and Controller.
Again, in this case the View is our prefs.xsl, Controler is prefs.html and Models are $PrefsForm, $registeredUser... objects.

I hope this clarified the whole thing a bit (even) more. The thing you should try to grasp is the MVC paradigm. Which is mainly what I am trying to implement in the framework. I choose XSL, because I believe XML is usefull at some point or another and because its more a technology I'd like to rely on than other "funky" template engines...

But our discussion brought me to the point that I realised I should automatically add the url the user requestes into the HttpResponse... It could be usefull, for say the left.xsl template to decide what context sensitiv menus to display.

Hope this helped to get my point over to you, don't hesitate to continue pushing yours that, even if I got to the point it doesn't follow the Model 2, it will help me bring the FrameWork to the most out there, rather than just for the solutions I am working on right now.
But the FrameWork is about to change, depending on PHP5, user reaction's on the pre-release I will make in a few weeks and people (including mine) requierement in the future...