Smarty is becoming more and more popular in the PHP community lately, especially as developers are moving away from mixing business and display logic in the same scripts and towards a cleaner MVC design pattern implementations.
If you’ve followed my blog for any amount of time, you’ll know that I’m currently working on my own CMS/Framework, to be completed hopefully in early 2007. I don’t know what it was – maybe procrastination – but something make me take a look back at my plugin implementation for the CMS.
Previously I took a rather odd, round-about way of including custom functions and plugin templates into my main pages:
Step 1: include the plugin template
Step 2: The plugin template called the template FUNCTION
Step 3: The function does a lot of business and assigns data to template variables
Step 4: the rest of the template is rendered with the newly-found data from the function
That’s a little too awkward, even for me!
It had to be simpler. Turns out the answer was always there…
The template functions (function.funcname.php : smarty_function_funcname() ) have the smarty object passed to them by reference, which means I can access anything Smarty from within that function. Jackpot! Here’s my newly preferred way of inserting these plugin data into your pages:
Step 1: call the plugin function directly from your main page template
Step 2: do all the businessy things, including assigning variables
Step 3: call $smarty->display(“plugin_template.tpl”) from within your plugin function
Why is this better? First, it’s more straightforward this way. It’s easier to pre-assign your templates directory in the header of your scripts and just call $smarty->display(). Second you can actually pass parameters to your function if you want (read: customizable/configurable plugin functionality). Want to have a choice of plugin templates depending on the output of your function, time of day, or little Jimmy’s iTunes playlist RSS syndication? No problem!
Elegant. Customizable. Smart!