Smarty templates and data shaping approaches by Mauro Molino
When developing PHP web applications, Smarty is my template engine of choice.
It is powerful, well supported and has a very neat syntax (or maybe I'm just
too used to it to see its drawbacks, but this is another story).
What I wanted to share is that sometimes, what seems to be(or really is) a
weakness of our tools can turn into virtue for our programming
style/methodology. Here, in brief, is the story.
I love the way you can manage arrays in PHP, it's so easy that you find
yourself almost involuntarily using them for every task. This can too easily
turn into addiction; soon you are building multidimensional arrays even when
not requested, and here is the trap. At a certain point you realize you're a
multidimensional arrays maniac. This is exactly what happened to me when I
found out I was managing an array like the following:
$products[$product_id']['categories']['assigned'][$assigned_category_id]
What I wanted to achieve on my presentation layer was to have a products table
with a nested assigned categories table for each product. Seemed easy enough,
but it wasn't. Though, as I wrote, Smarty is my favourite template engine, I
cannot assert I'm a Smarty guru, so after half an hour of attempts I came out
with some more or less working template snippet that, for decency, I'm not
going to publish here. Now let's ignore that an expert (at least more expert
than me) Smarty user would have solved it easily, what I realized in the end is
that maybe my approach to data shaping was not correct. I tried to compare the
situation to typical database approaches. More than probably, I thought, if
using a db engine I would have created two tables, one with the products and
one with assigned categories bound to a specific product (being the product_id
the foreign key).
I tried to follow that pattern, split my array in two, and after 3 minutes I
had a perfectly working template without the need for tricks on Smarty.
Does this mean my data model was unnecessarily complicated? I don't know, and
would gratefully appreciate others' opinions, but I suspect I've learnt a
lesson.......
About the Author
Mauro is a professional developer, platform integration evangelist, free
information supporter and owner/webmaster of beanizer.org.
When not developing software, he composes music, mainly for the theatre.
|