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

jq6vz3qz  于 7个月前  发布在  其他
关注(0)|答案(4)|浏览(99)

我想在助手中创建新函数,但仍然失败: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但它仍然不工作

nkcskrwz

nkcskrwz1#

它没有在文档中提到,但请记住添加后缀**_helper到您的助手的文件名,否则它将无法在codeigniter 4中工作。
例如,如果您已经创建了一个助手
xxx.php**,请将其更改为xxx_helper.php
要加载助手,可以使用helper函数(如:helper('xxx.php');)或将其添加到BaseController中受保护的属性**$helpers**数组中

nhjlsmyf

nhjlsmyf2#

如果你的想法是“扩展”(替换)stystem/helpers/text_helper上的一个函数,注意文件名中的后缀,你必须尊重它。
另外,helper不需要命名空间,helper loader会搜索它。
helper()方法将扫描app/Config/Autoload.php中定义的所有PSR-4命名空间,并加载所有匹配的同名helper。这允许加载任何模块的helper,以及您专门为此应用程序创建的任何helper。加载顺序如下:

  1. app/Helpers -此处加载的文件总是首先加载。
    1.{namespace}/Helpers -所有命名空间都按照定义的顺序循环。
  2. system/Helpers -最后加载基本文件
    命名空间将用于在其他位置加载帮助程序,例如:
helper('Libraries\MyFunctions');

字符串
只要可以通过PSR-4中设置的名称空间找到该路径
参考:https://codeigniter4.github.io/userguide/general/helpers.html#extending-helpers

6rvt4ljy

6rvt4ljy3#

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

rmbxnbpk

rmbxnbpk4#

  • 在CodeIgniter版本中测试:4.4.3*
    第一步:

"App\Helpers"目录中创建一个名为"custom_helper.php"的Helper。

第二步:

通过删除此文件中的"_helper.php"打开"App\Config\Autoload.php"和Created Helper名称。

public $helpers = [
        'custom', // Helper Name: custom_helper.php
    ];

字符串
File:zh-hans-history.php

<?php
function hello(){
   echo "Hello Function";
}
?>

**Step-3:**All Done!现在我们可以使用函数名从控制器调用我们的函数Example: hello()

相关问题