0

I'm quite new to Joomla. I have a component with multiple different models and views, but a few of them use the same functions. Right now I have those functions copied in every model file, but I'd prefer to just have a single file with those functions.

After looking up solutions on the internet, the right way to do it seems to be to create a helper class somewhere in the component, but there's so much contradictory information that I'm not sure where I'm supposed to put it, and how to access it from my model files.

My component has a "site" directory, and in it, there are "models" and "views". I added a third folder, "helpers". Inside it, I made a MyHelper.php file like this:

defined('_JEXEC') or die;

class MyHelper
{
    public static function meep()
    {
        echo "Meep! Helper works!";
    }
}

But how do I access it from inside my model php files? I've tried various pieces of code I found online, but nothing seems to work.

First, I tried putting this line in my model file:

use Joomla\Component\[my component name]\Site\Helper\MyHelper;

and then later inside a function:

MyHelper::meep();

However, when I open the page, I get this error right in the page title:

Class "Joomla\Component\[my component name]\Site\Helper\MyHelper" not found

So I tried replacing that "use" line with this, which I found somewhere else on the internet:

JLoader::register('MyHelper', JPATH_SITE . '/components/com_[my component name]/helpers/MyHelper.php');

And now the error is simply:

Class "MyHelper" not found

What am I doing wrong?

1

1 Answer 1

0

From the description of your component structure, it sounds like it was designed for an older version of Joomla, as it doesn't appear to use namespacing.

Namespacing is recommended for Joomla 4 and is required for Joomla 5.

You appear to be trying to use a namespace to call the helper file in a component that doesn't use namespaces, so the system fails to find the required file.

To call the helper without a namespace, you just require_once() the file:

require_once(JPATH_COMPONENT . '/helpers/MyHelper.php');

Then your helper methods should be available to you MyHelper::meep()

1
  • Thanks! Yes, the component was made for Joomla 3, but it surprisingly worked for Joomla 4 after some very minor changes. And I actually made another, very simple mistake here. I forgot to start with <?php at the beginning of the helper's php file. Now everything's working well :) Mar 25 at 13:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.