Helpers
Overview
A helper class is a class filled with static methods and is usually used to isolate a "useful" algorithm. They are used to assist in providing some functionality, though that functionality isn't the main goal of the application. They're also used to reduce the amount of redundancy in your code.
Implementation
Helper classes are stored in the helper
sub-directory of your component directory. Naming convention typically follows a pattern of {ComponentName)Helper(HelperName}. Therefore, our helper class is called HelloHelperOutput
.
Here's our com_hello/helpers/output.php
helper class:
<?php // No direct access defined( '_JEXEC' ) or die( 'Restricted access' ); jimport('joomla.application.component.helper'); /** * Hello World Component Helper * * @package Joomla.Tutorials * @subpackage Components */ class HelloHelperOutput { /** * Method to make all text upper case * * @access public */ public function shout($txt='') { return strToUpper($txt).'!'; } }
We have one method in this class that takes all strings passed to it and returns them uppercase with an exclamation point attached to the end. To use this helper, we do the following:
class HelloViewHello extends JView { function display($tpl = null) { include_once(JPATH_COMPONENT.DS.'helpers'.DS.'output.php'); $greeting = HelloHelperOutput::shout("Hello World"); $this->assignRef( 'greeting', $greeting ); parent::display($tpl); } }