如何在 Laravel 中创建自定义辅助函数 [英] How to create custom helper functions in Laravel

查看:33
本文介绍了如何在 Laravel 中创建自定义辅助函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建辅助函数以避免在 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"
]

这篇关于如何在 Laravel 中创建自定义辅助函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆