Documentation

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 helpers sub-directory of your component folder. As with all other classes, naming follows the PSR-0 convention and are within the Components namespace. Therefore, our helper class is called Components\Hello\Helpers\Output.

Here's our com_hello/helpers/output.php helper class:

<?php

namespace Components\Hello\Helpers;

/**
 * Hello World Component Helper
 */
class Output
{
	/**
	 * Method to make all text upper case
	 *
	 * @param  string  $txt
	 * @return  string
	 */
	public static 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:

<?php

namespace Components\Hello\Site\Controllers;

use Hubzero\Component\SiteController;
use Components\Hello\Helpers\Output;

class Greetings extends SiteController
{  
	public function displayTask()
	{
		include_once(dirname(dirname(__DIR__)) . DS . 'helpers' . DS . 'output.php');

		$greeting = Output::shout("Hello World");  

		$this->view
                  ->set( 'greeting', $greeting )
                  ->display();  
	}  
} 

Last modified:

  • Copyright © 2022 Hubzero
  • Powered by Hubzero®