简体   繁体   中英

How to create and load new helper in CodeIgniter 4

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

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

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:

  1. app/Helpers - Files loaded here are always loaded first.
  2. {namespace}/Helpers - All namespaces are looped through in the order they are defined.
  3. 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

You need to load the helper into the app/Config/Autoload.php and still not work then please try to run composer dump-autoload

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM