Extended Setup

This is a continuation of the basic installation, please read that first!

A slightly more flexible way to setup Smarty is to extend the class and initialize your Smarty environment. So instead of repeatedly setting directory paths, assigning the same vars, etc., we can do that in one place. Lets create a new directory "/php/includes/guestbook/" and make a new file called "setup.php".

Example 2-8. Editing /php/includes/guestbook/setup.php


// load Smarty library files
define('SMARTY_DIR','/usr/local/lib/php/Smarty/');
require(SMARTY_DIR.'Smarty.class.php');

// a good place to load application library files, example:
// require('guestbook/guestbook.lib.php');

class Smarty_GuestBook extends Smarty {

   function Smarty_GuestBook() {
   
   		// Class Constructor. These automatically get set with each new instance.

		$this->Smarty();

		$this->template_dir = '/web/www.mydomain.com/smarty/guestbook/templates/';
		$this->compile_dir = '/web/www.mydomain.com/smarty/guestbook/templates_c/';
		$this->config_dir = '/web/www.mydomain.com/smarty/guestbook/configs/';
		$this->cache_dir = '/web/www.mydomain.com/smarty/guestbook/cache/'; 
		
		$this->caching = true;
		$this->assign('app_name','Guest Book');
   }

}

Technical Note: In our example, we keep application libraries (not intended for direct browser access) in a separate directory outside of the document root. These files may contain sensitive data that we don't want any direct access to. We keep all library files for the guest book application under "/php/includes/guestbook/" and load them in the setup script, as you see in the above example.

Now lets alter the index.php file to use setup.php:

Example 2-9. Editing /web/www.mydomain.com/docs/guestbook/index.php


require('guestbook/setup.php');

$smarty = new Smarty_GuestBook;

$smarty->assign('name','Ned');

$smarty->display('index.tpl');

Now you see it is quite simple to bring up an instance of Smarty, just use Smarty_GuestBook which automatically initializes everything for our application.