5.2. New resources

In OPT, the programmer may use not only files as a template resource. The parser allows to write your own resource handling function, reading the templates from the database etc. Its structure is very simple. The function accepts three parameters:

  1. optClass object.
  2. The name of the template.
  3. Optional compiled file modification time.

The function returns the template source or false, if it is already compiled. In order to handle the situation, when the template does not exist, the function may call the optClass::error() method, which generates an exception. In the example we can see a sample database resource:

Example 5.2. New OPT resource

<?php
	 
	 function optResourceDatabase(optClass $tpl, $title, $compiledTime = NULL)
	{
		if(is_null($compiledTime))
		{
			$r = mysql_query('SELECT `code` FROM `templates`
				WHERE `title` = \''.$title.'\'');
		}
		else
		{
			$r = mysql_query('SELECT `code` FROM `templates`
				WHERE `title` = \''.$title.'\' AND
				`lastmod` > \''.$compiledTime.'\'');
		}
		if($row = mysql_fetch_row($r))
		{
			return $row[0];		
		}
		return false;	
	} // end optResourceDatabase();
											  
?>

The prefix of the function is optResource. It may be registered with optClass::registerResource() method:

$tpl -> registerResource('db', 'Database');

The first parameter is the handle. Using it, we can tell the parser that this template is located in the specified resource:

$tpl -> parse('db:sample_template');

Note that the file handle is reserved for the default OPT resource, although you do not have to specify it while calling the templates.