Ugly Code
Currently, I’m assigned to maintain a website that was written in PHP several years ago with PostgreSQL as its database. It was originally written in mixed up PHP and HTML (not even XHTML).
Good thing is that my officemates who maintain the project used Smarty templating engine to fully separate the PHP codes and the HTML codes. Yes it’s beautiful!
So now, they are busy for the other project, and me assigned to handle some updates. I am creating a module very similar to an existing module but with separate database table.
However, the module I am copying was written in mixed PHP + HTML so I have to dissect every part so that I could separate them into templates. Smarty is so easy.
Smarty Overview
Here is how Smarty works.
- Download Smarty library and put it on your project library directory
- Create a template directory and the template cache directory (Read Manual)
- Create templates for your pages. (It could be a whole page, or a portion of a page such as header, footer, navigation, menu, etc)
- Pass data from your PHP code to your smarty templates by of course reading the manual.
Sample:
//Include the Smarty library base class to your script: require_once "../lib/MySmarty.class.php"; //instantiate object $smarty = new MySmarty(); //assign data to your template $topData = array('id' => 1, 'name' => 'Test'); $smarty->assign('top_data', $topData); unset($topData); //render template (located inside template directory) $smarty->display("page1.tpl");
The page1.tpl will usually looks like this:
<html> <head> <title>Page 1</title> </head> <body> <p>ID: {$top_data.id}</p> <p>Name: {$top_data.name}</p> </body> </html>
Hmmm…thank you for this post. With this, I was able to implement smarty on my ZF application.
My question is, if you will be using .tpl for your view, what will happen to your .phtml? Will it be always be blank (since you are using smarty, you won’t be needing this right?)?
Thanks.
Sorry for the very very late reply. My site is down for two weeks.
Regarding your question, I don’t actually know what will happen to .phtml, I haven’t tried it yet. However, if you are going to use Smaty + Zend Framework, that would be too much bloat since there will be additional files to include and additional parsing (Smarty Parsing).
However, if it is worth it, then go ahead with Smarty. Sorry if I can’t answer your question, I have no experience on it yet.