Smarty plugin: module

Tagged: PHP, Programming Date: 7th, November 2008

Some time ago I wrote this useful smarty plugin wich will enable you to call method of any php class from smarty html template.
It’s very simple and it goes:

/**
 * @author Vladimir Cvetic < vladimir[at]ferdinand.rs >
 */
function smarty_function_module($params, &$smarty)
{
	/* Check if required params are valid */
	if (!isset($params['class']))
	{
		$smarty->trigger_error('Module name is not defined!');
		return false;
	}
	if (!isset($params['method']))
	{
		$smarty->trigger_error('Method name is not defined!', E_USER_ERROR);
		return false;
	}
	elseif (!method_exists($params['class'],$params['method']))
	{
		$smarty->trigger_error('Method is not defined in module! -> '. $params['class'].'::'.$params['method'], E_USER_ERROR);
		return false;
	}

	return call_user_func($params['class'].'::'.$params['method'], $params);
}

Example usage:
{module class=”CLASS_NAME” method=”CLASS_METHOD_NAME” param1=”string1″ param2=77}

Your class method will receive one parameter (associative array), which will contain all parameters passed to smarty function. I this example array would look like this:

Array
(
    [class] => 'CLASS_NAME'
    [method] => 'CLASS_METHOD_NAME'
    [param1] => 'string1'
    [param2] => 77
)

To install this plugin simply create file named function.module.php in smarty plugins folder and copy&paste function to that file.

Leave a Reply