Skip to content
tedkulp edited this page Apr 29, 2011 · 3 revisions

Helpers are basically functions designed specifically to help our your views. They're the little functions that fix formatting, or convert text or any other view related function that goes beyond the data coming from the controller.

Helpers are simple classes inherited from the \silk\display\Helper class. The default application skeleton, however, contains an additional ApplicationHelper class that is created when the application is first created. New controller specific helper classes then by default should extend ApplicationHelper instead in order to maintain consistency and have all of those "global" helpers available in the single helper object.

When the controller's action method is ran, the controller will look to see if a helper class exists, and if the ApplicationHelper class exists in it's absence. It will then take the helper class, instantiate it, and put it into the $helper variable in your view.

For an example, let's assume we have a TestController class (app/controllers/TestController.php). We then create a helper class for this controller in app/helpers/TestHelper.php. The code could look something like:

class TestHelper extends ApplicationHelper
{
  function format_date($time)
  {
    return strftime("%Y-%m-%d %H:%M", $time);
  }
}

This is a very simple helper that will take a given unix time, and make a pretty version for display in your view. To use it, you could simply do something like so in your view:

<p>The time is now <?php echo $helper->format_time($some_time) ?></p>

Or if you're using a smarty template:

<p>The time is now {$helper->format_time($some_time)}</p>

Smarty Helpers

Another thing we can do if you're using a smarty template is create smarty plugins automatically from helper functions. If the function name starts with function, modifier or block, a corresponding smarty plugin will be created based on that type. So, for example, supposed to create a helper method that begins with modifier.

class TestHelper extends ApplicationHelper
{
  function modifier_my_format_date($time)
  {
    return strftime("%Y-%m-%d %H:%M", $time);
  }
}

If you're using a smarty template, you should then be able to automatically do:

<p>The time is now {$some_time|my_format_date}</p>

The smarty plugin types require the following function definitions:

  • Function - function function_my_plugin_name($params, $template)
  • Modifier - function modifier_my_plugin_name($value, $param1, $param2, ...)
  • Block - function block_my_plugin_name($params, $content, $template, &$repeat)

Also, the naming scheme for Smarty helper functions does not follow Silk's camelCase and instead follows the traditional underscore_naming_scheme. This is for compatibility reasons with Smarty's libraries.

For more information on Smarty plugin creation, check out Chapter 16 in the Smarty manual.

Clone this wiki locally