如何在 Laravel 中创建自定义辅助函数

2022-01-30 00:00:00 php laravel laravel-helper

我想创建辅助函数以避免在 Laravel 中的视图之间重复代码.例如:

I would like to create helper functions to avoid repeating code between views in Laravel. For example:

view.blade.php

<p>Foo Formated text: {{ fooFormatText($text) }}</p>

它们基本上是文本格式化功能.我应该如何定义全局可用的辅助函数,例如 fooFormatText()?

They're basically text formatting functions. How should I define globally available helper functions like fooFormatText()?

推荐答案

在你的 app 文件夹中创建一个 helpers.php 文件并用 composer 加载它:

Create a helpers.php file in your app folder and load it up with composer:

"autoload": {
    "classmap": [
        ...
    ],
    "psr-4": {
        "App\": "app/"
    },
    "files": [
        "app/helpers.php" // <---- ADD THIS
    ]
},

将其添加到您的 composer.json 文件后,运行以下命令:

After adding that to your composer.json file, run the following command:

composer dump-autoload


如果您不喜欢将 helpers.php 文件保存在 app 目录中(因为它不是 PSR-4 命名空间的类文件),您可以执行以下操作laravel.com 网站:存储 helpers.php 在引导目录中.记得在你的 composer.json 文件中设置它:


If you don't like keeping your helpers.php file in your app directory (because it's not a PSR-4 namespaced class file), you can do what the laravel.com website does: store the helpers.php in the bootstrap directory. Remember to set it in your composer.json file:

"files": [
    "bootstrap/helpers.php"
]

相关文章