I'm having trouble with using a helper file in Joomla 4, I'm not really sure where I'm going wrong.
I have a helper file in my template, like templates/mytemplate/html/helper.php
and this works well within my template, using JLoader::register('myhelper', 'templates/mytemplate/html/helper.php');
and myhelper::testfunc("hello");
sort of thing.
Where I've hit a bump, is that I want to also use functions from this helper file elsewhere, for example, in a joomla console command. When I use the same code in my console I just Class not found
errors.
I've tried quite a few variations of JLoader
, like registerPrefix
, registerNamespace
and setup
, and some use
commands to pull in the namespace, with no luck. I also tried moving the helper into a library, but that didn't work either.
I think I'm missing something re Joomla 4 and namespaces, any ideas?
Some code, to help explain...
The template helper templates/mytemplate/html/myhelper.php
<?php
/**
* This is a helper file
* Usage:
* Register it like...
* JLoader::register('myhelper', 'templates/mytemplate/html/myhelper.php');
* Call functions like...
* myhelper::tester("hello");
*/
namespace Myhelper; # not sure about this bit
class Myhelper{
/**
* tester
* @param string test string
* @return string output string
*/
public static function tester($test_value){
return "tester says " . $test_value;
}
}
The console code plugins/system/myconsole/src/Console/MyconsoleCommand.php
<?php
/**
* Call like...
* php cli/joomla.php myconsole:action hello
*/
namespace Joomla\Plugin\System\Saaconsole\Console;
\defined('JPATH_PLATFORM') or die;
use Joomla\CMS\Factory;
use Joomla\Console\Command\AbstractCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use JLoader;
class MyconsoleCommand extends AbstractCommand
{
# some console boilerplate is here, removed for brevity
protected function doExecute(InputInterface $input, OutputInterface $output): int
{
# some console boilerplate is here, removed for brevity
JLoader::register('myhelper', 'templates/mytemplate/html/myhelper.php');
$test = myhelper::tester("galopin");
$symfonyStyle->text('test: ' . $test);
return 0;
}
}
This code comes back with [Error] Class "Joomla\Plugin\System\myconsole\Console\myhelper" not found