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

查看:79
本文介绍了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?

推荐答案

在您的应用文件夹中创建一个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 5中自定义助手的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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