2
Posted September 29, 2009 by Spyros in PHP Programming
 
 

Using Smarty as a Template Engine For Your Php Websites

2
2

Many programmers take up web programming at least once in their lives. Almost all of them, including myself of course, do it the wrong way at our first attempt. The first thing we learn is HTML along with CSS and then most move to PHP and mySQL in order to make dynamic websites. The one and most important mistake we make is writing HTML AND PHP in the same pages, creating a very bad mixture of unmaintanable code. Moreover, we are not that knowledgeable on creating website templates that work well and tend to write the same code over and over again. I’ll be attempting to explain how to avoid this, giving you some insight on how to propery code your websites so that you clear clear and easily maintanable code.

Smarty Template System – A must for web programmers

Smarty( http://www.smarty.net/ ) has become today’s standard for a template engine. But what is it really? In fact, in simple words smarty is a way to differentiate programming code from represantation of data. Imagine that for every php page, there is a template that is responsible for presenting what is needed to print on the browser. For instance, you find in your php file that you need to do something like:

<title> <?php print("$title"); ?> </title>

There are many people who, in an attempt to create such changing titles do that, but this is a very bad programming habit and let me explain why. First of all, you include php and html on the same php page. This makes it hard to read and if code becomes larger, it will really be a mess. Moreover, what happens if we need to add mySQL, or PEAR or whatever other extension? It would really be hell for the programmer after 1000 lines or even less. Using Smarty, you can do something else. Say that you have an index.php and an index.tpl file. You then write something like that on the two files:

(in Smarty syntax)

index.php :

$smarty->assign('My first Website', $title);

and then in index.tpl:

<title>{$title}</title>

Do you see the great power? You can now just change either the representation or the data itself using the separate files. You no longer mess with a single php file that contains everything in a very ugly way.

So, how do i install smarty?

Most probably it is already installed by your webhost, but if not, you can easily download it and add it just outside your web root, in your home dir. This is how i did it for the websites i have created in the past :

I have a file named smartySetup.php that contains the below:

<?php

define('SMARTY_DIR','smarty/libs/');
require_once(SMARTY_DIR."Smarty.class.php");
require_once 'config.php';

class SmartyGame extends Smarty
{

    function __construct() {
        parent::__construct();

        $this->template_dir = $GLOBALS['config']['SmartyDir'].'/templates/';
        $this->compile_dir  = $GLOBALS['config']['SmartyDir'].'/templates_c/';
        $this->config_dir   = $GLOBALS['config']['SmartyDir'].'/configs/';
        $this->cache_dir    = $GLOBALS['config']['SmartyDir'].'/cache/';

        $this->caching = false;
        $this->assign('appName', $GLOBALS['config']['AppName']);
        $this->assign('appVersion', $GLOBALS['config']['AppVersion']);
    }
}

?>

This is the page that i include in my main index.php page, usually right after i begin a session(if needed). Let me now explain what this file does. At first, we include the Smarty.class.php, which is under $PATH/smarty/libs/Smarty.class.php($PATH includes my host account home of course).

Then, i include my config.php with information about mySQL tables and such. Then, i create the constructor to the smartyClass, defining the templates folder that holds our created tpl files, the templates_c(used as a cache file), the cache file itself and the configs folder(used for things like language altering and such). However, i tend to disable smarty caching mechanism as you see. Finally, i assign two variables from config.php which i use to describe my appName and appVersion.

Then, to use it, i create a singleton like function that instantiates the object. In case you do not know, Singleton is a well known design pattern used in order to have an object that does not reinstantiate upon declaration. For instance, if you execute “$smarty = new SmartyGame();” two or more times under Singleton pattern, you always get the same object and not a new one. The function i use is like:

function smartyObject()
{
    if ($GLOBALS['config']['SmartyObj'] == 0)
    {
        $smarty = new SmartyGame();
        $GLOBALS['config']['SmartyObj'] = $smarty;
    }
    else
        $smarty = $GLOBALS['config']['SmartyObj'];
    return $smarty;
}

I highly suggest that you use Smarty from now on. It will not only enable you to create better code but will make web coding much easier for you. That was all :) Thanx for reading and as always, for any questions don’t hesitate to contact me through private message or mail.


Spyros