Laravel 5 中自定义助手的最佳实践 [英] Best Practices for Custom Helpers in Laravel 5

查看:28
本文介绍了Laravel 5 中自定义助手的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to create helper functions to avoid repeating code between views in Laravel 5:

view.blade.php

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

它们基本上是文本格式功能.我在哪里以及如何使用这些功能创建文件?

They're basically text formatting functions. Where and how can I create a file with these functions?

推荐答案

在你的 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"
]


提示:如果您想使用不同的文件名而不是 helpers,您可以更改文件名和路径.此外,您可以创建多个帮助文件.它看起来像这样:


Tip: If you want to use the different file name instead of helpers, you can change the file name and path. Also, you can create multiple helper files. It will look like this:

"autoload": {
    "classmap": [
        ...
    ],
    "psr-4": {
        "App\": "app/"
    },
    "files": [
        "app/Helpers/base.php", // <---- ADD THIS
        "app/Helpers/metrics.php" // <---- Create `metrics.php` file in this path and add the path in composer.json file.
    ]
},

这篇关于Laravel 5 中自定义助手的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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