Reputation: 45
i want to create new function in helper, but it still failed :
Call to undefined function
i save my helper at app/Helper/Text_helper.php
using namespace App\Helpers;
and load helpers on BaseController using protected $helpers = ['text'];
Reference : https://codeigniter4.github.io/userguide/general/helpers.html#extending-helpers but it's still not working
Upvotes: 3
Views: 8000
Reputation: 365
To add to all the answers here:
As per Codeigniter4 documentation, you can create a custom helper with the name:
myname_helper.php
And load it in your controller before loading the view, like this:
helper('myname');
And then access its function(s) in controller or view like this:
myhelperfunction();
I would recommend to keep an eye on the documenation though :)
Upvotes: 0
Reputation: 2529
Tested in CodeIgniter Version: 4.4.3
Step-1:
Create a Helper named "custom_helper.php"
in the "App\Helpers"
Directory.
Step-2:
Open "App\Config\Autoload.php"
and the Created Helper name by removing "_helper.php"
in this file.
public $helpers = [
'custom', // Helper Name: custom_helper.php
];
File: custom_helper.php
<?php
function hello(){
echo "Hello Function";
}
?>
Step-3:
All Done! Now we can call our function Example: hello()
from controller using the function name.
Upvotes: 1
Reputation: 307
It's not mentioned in documents but remember to add a suffix _helper to filename of your helper otherwise it will not work in codeigniter 4.
For example if you have created a helper xxx.php, change it to xxx_helper.php.
To load a helper you can use helper function (Like: helper('xxx.php');
) or add it to $helpers array that is an protected property in BaseController
Upvotes: 8
Reputation: 131
If your idea is to "extend" (replace) a function on the stystem/helpers/text_helper note the lowercase in the name of the file, you have to respect it.
Also, the helper doesn't need a namespace... the helper loader will search for it.
The helper() method will scan through all PSR-4 namespaces defined in app/Config/Autoload.php and load in ALL matching helpers of the same name. This allows any module’s helpers to be loaded, as well as any helpers you’ve created specifically for this application. The load order is as follows:
- app/Helpers - Files loaded here are always loaded first.
- {namespace}/Helpers - All namespaces are looped through in the order they are defined.
- system/Helpers - The base file is loaded last
the namespace will be used to load a helper on other location, for example:
helper('Libraries\MyFunctions');
as long as that path can be found through a namespace that has been set up within the PSR-4
Reference: https://codeigniter4.github.io/userguide/general/helpers.html#extending-helpers
Upvotes: 1
Reputation: 474
You need to load the helper into the app/Config/Autoload.php and still not work then please try to run composer dump-autoload
Upvotes: 0