Posts Tagged php smarty

Fetch Smarty Templates From MySQL Database

I was recently working on a mailing application. With the nature of the bulk mailing routine, it was designed to store templates made by its users and email designers. Since most of them have been exposed to Smarty templating before we decided to base our email template parsing to Smarty.

Smarty does not come with the ability to parse templates from database natively, but it is easy to extend it to do just that.

DISCLAIMER: This is a quick and dirty hack I provided with my colleagues. Improvement required!

This approach should work on both PHP 4 and PHP 5, since Smarty.class.php is written on PHP 4.

What we will need to do is extend Smarty.class.php on a new class and override function _fetch_resource_info and replace the if clause demonstrated below to use our code that actually fetches database stored templates.

class Smarty
{
    function _fetch_resource_info(&$params) {
        ....
        if ($this->_parse_resource_name($_params)) {
            .....
        }
        ....
    }
}

Our resulting class would look something like:

require_once 'Smarty.class.php';

class Smarty_Db extends Smarty
{
    function _fetch_resource_info(&$params) {
        ....
        $_resource_type = $_params['resource_type'];
        $_resource_name = $_params['resource_name'];

	$db = new Template_Db;
	if ($params['get_source']) {
            $params['source_content'] = $db->fetchTemplate($myTemplateId);
        }
	$params['resource_timestamp'] = now();
        $_return = true;
        ....
    }
}

So you would then use your Smarty extended class like:

$smarty = new Smarty_Db;
$smarty->compile_dir = '/path/to/my/compile/dir';

$compiledTemplateFromDb = $smarty->fetch($myTemplateId);

That is all there is to it actually. I haven't went through all the Smarty pre and post processing, but this should suffice the requirements for now.

Hope this helps.

, ,

No Comments