Best Practices for Custom Helpers in Laravel 5

后端 未结 20 1980
暖寄归人
暖寄归人 2020-11-22 06:40

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

view.blade.php

Foo Formated text: {{ fo

20条回答
  •  北海茫月
    2020-11-22 07:20

    Best Practice to write custom helpers is

    1) Inside the app directory of the project root, create a folder named Helpers (Just to separate and structure the code).

    2) Inside the folder write psr-4 files or normal php files

    If the PHP files are in the format of psr-4 then it will be auto loaded, else add the following line in the composer.json which is inside the project root directory

    Inside the autoload key, create a new key named files to load files at the time of auto load,inside the files object add the path starting from app directory., here is an example.

    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        },
        "files": [
            "app/Helpers/customHelpers.php"
        ]
    },
    "autoload-dev": {
        "classmap": [
            "tests/TestCase.php"
        ]
    },
    

    PS : try running composer dump-autoload if the file dosen't loaded.

提交回复
热议问题