I've tried to autoload the helper function. I've added the helper file in autoload.php and called the function in the view file, but it's not working.
app/Config/autoload.php
$psr4 = ['Config' => APPPATH . 'Config',
APP_NAMESPACE => APPPATH,
'App' => APPPATH,
'Helpers' => APPPATH . 'Helpers/MY_helper'];
app/Helpers/My_helper.php
<?php if(!defined('BASEPATH')) exit('No direct script access allowed');
function chicking_helper(){
return 'welcome to helper function';
}
app/Views/welcome_message.php
<h1>Welcome to CodeIgniter </h1>
<p class="version">version <?= CodeIgniter\CodeIgniter::CI_VERSION ?></p>
<?php
chicking_helper();
?>
app/Controllers/BaseController
class BaseController extends Controller
{
/**
* An array of helpers to be loaded automatically upon
* class instantiation. These helpers will be available
* to all other controllers that extend BaseController.
*
* @var array
*/
protected $helpers = ['url', 'file'];
In your BaseController - $helpers array, add an element with your helper filename. Say you have it as app/Helpers/My_helper.php
, then you edit your BaseController like this:
class BaseController extends Controller
{
/**
* An array of helpers to be loaded automatically upon
* class instantiation. These helpers will be available
* to all other controllers that extend BaseController.
*
* @var array
*/
protected $helpers = ['url', 'file', 'my_helper'];
You do not need to touch the Autoload class in your scenario. It is used to map all the different namespaces in your project.
app/Helpers/My_helper.php
if(!function_exists('chicking_helper')) {
function chicking_helper(){
return 'welcome to helper function';
}
}
Codeigniter 4 documentation helpers