The Problem: How It Works vs. How it Looks

Tags:

I have used PHP to power web-sites with dynamic content now for many years and for all that time I have been dissatisfied with how difficult it has been to keep separate the concerns of how the sites look from how the sites work. I've seen people refer to this topic as "presentation logic" verses "business logic", but whatever it is called the problem, to me, always comes down to "how does it look" vs. "how does it work".

For years I thought that the way to keep the look separate from the workings was to work hard to keep the PHP separate from the HTML: HTML dictates how things look, PHP dictates how things work. To that end I settled on a PHP template class that parsed HTML files with minimally intrusive additional mark-ups, typically keywords wrapped in "{ }". I found the class on the Internet, and it was kind of complex, and I never really bothered to understand what, exactly, it was doing, I just figured out how to fix it when it broke whenever I upgraded to a newer version of PHP. I never even bothered to learn how to use more than a minimal subset of its capabilities, it was just too much work after already having had to learn HTML, PHP, SQL and eventually CSS (Cascading Style Sheets).

Speaking of CSS, I thought at first that these were the godsend I was looking for that would finally let me separate how web-sites looked verses how they worked. After all, look at the amazing things in CSS Zen Garden that you can do with CSS-based design. And while designing sites with CSS in mind did let me simplify things some, they really didn't address my fundamental problem.

Recently I stumbled upon an article by Brian Lozier, Beyond The Template Engine, in which he complains about the same problem and proposes a solution. His solution is simple and obvious in hindsight, but for whatever reason it took me all these years to see the light. Rather than using a separate pseudo-scripting language for creating complicated template structures he uses PHP itself. His argument is clear and sound, so I won't bother repeating it. But the conclusion deserves repeating, and that is this: the problem is not keeping the HTML separate from the PHP, the problem is keeping how things look, or the "presentation logic", separate from how things work, or the "business logic". Once you realize that, and you realize that learning a tiny number of PHP constructs is no more difficult than learning the grammar of yet another half-language (i.e., the template-engine's grammar), especially if you the programmer are the person responsible for the look of your site, too, then the rest is liberating.

So without further ado, here is a template "engine" that is so simple you'll wonder why everybody doesn't already see this as obvious.