Laravel中自定义辅助函数

799 阅读1分钟

辅助函数文件位于/bootstrap文件夹下

1. 新建bootatrap/helpers.php文件,写入如下测试用的辅助方法。

function test_helper() {
    return 'hello world';
}


2. 接着我们需要使用composer 的 autoload 功能来自动引入helpers.php文件,也就是在composer.json文件中加载我们自定义的helpers.php文件

打开 composer.json 文件,并找到 autoload 段,将其修改为:

 "autoload": {
        "classmap": [
            "database/seeds",
            "database/factories"
        ],
        "psr-4": {
            "App\\": "app/"
        },
        "files": [
            "bootstrap/helpers.php"
        ]
    },

注意逗号不要多写或者漏写。


3. 接着命令行执行 composer dumpautoload 重载依赖

4. 最后在命令行中使用Laravel中自带的tinker工具进行调试

php artisan tinker

test_helper()

'hello world'

证明辅助函数自定义成功!