Connecting a frontend helper in a custom Joomla 3 component

Connecting a frontend helper in a custom Joomla 3 component

There are three places to make using a helper file work for you. First make sure you have a ‘helpers’ directory at the root of your component and that a base file (min) exists, usually called the same as your component, without the com_ prefix. e.g. com_example you would have com_example/helpers/example.php. Once this is done, insert whatever class you might want to call on.

See the following example for example.php

<?php
defined('_JEXEC') or die;

abstract class ExampleHelper
{
  public static function myFunction()
  {
    $result = 'Something';
    return $result;
  }
}
?>

Now let’s add a call to the class within a view to attempt to get some value out. Here I’m attempting to output at com_example/views/viewName/tmpl/default.php. It might be called something else for you.

<?php
$blurb = ExampleHelper::myFunction();
echo $blurb;
?>

Voila! Nothing happens, actually we get a nasty error notification, CLASS NOT FOUND type thing, ouch! So we need one more piece to make sure the call in the view (output to screen) can find the class we want to take information from and possibly even pass info into those functions, methods, etc.

Traditionally Joomla (3) tells us to add our last piece of code to the root example.php file found at com_example/example.php. Add it after your main controller call, like the following.

jimport('joomla.application.component.controller');

require_once JPATH_COMPONENT . '/helpers/example.php';  //<-- this is our missing code that will tie things together between the view and the helper

// Execute the task.
$controller	= JControllerLegacy::getInstance('Example');
$controller->execute(JFactory::getApplication()->input->get('task'));
$controller->redirect();

Anyway this is more of a note for myself here, but hope it helps someone else out in the Joomla 3 wild.