如何在 CodeIgniter 4 中创建和加载新的助手

How to create and load new helper in CodeIgniter 4

我想在 helper 中创建新函数,但还是失败了: Call to undefined function

我使用 namespace App\Helpers; 将我的助手保存在 app/Helper/Text_helper.php 并使用 protected $helpers = ['text'];

在 BaseController 上加载助手

参考:https://codeigniter4.github.io/userguide/general/helpers.html#extending-helpers 但还是不行

您需要将 helper 加载到 app/Config/Autoload.php 但仍然无法正常工作,请尝试 运行 composer dump-autoload

如果您的想法是“扩展”(替换)stystem/helpers/text_helper 上的函数,请注意文件名中的小写字母,您必须尊重它.

此外,助手不需要命名空间...助手加载程序将搜索它。

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

命名空间将用于在其他位置加载助手,例如:

helper('Libraries\MyFunctions');

as long as that path can be found through a namespace that has been set up within the PSR-4


参考: https://codeigniter4.github.io/userguide/general/helpers.html#extending-helpers

它在文档中没有提到,但请记住在您的助手文件名中添加后缀 _helper 否则它将无法在 codeigniter 4 中工作。

例如,如果您创建了一个助手 xxx.php,请将其更改为 xxx_helper.php.

要加载助手,您可以使用 helper 函数(如:helper('xxx.php');)或将其添加到 $helpers 数组这是 BaseController

中受保护的 属性