Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

php - Best Practices for Custom Helpers in 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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
    ]
},

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

composer dump-autoload

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"
]

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.
    ]
},

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...