Best Practices for Custom Helpers in Laravel 5

后端 未结 20 1991
暖寄归人
暖寄归人 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

    In laravel 5.3 and above, the laravel team moved all procedural files (routes.php) out of the app/ directory, and the entire app/ folder is psr-4 autoloaded. The accepted answer will work in this case but it doesn't feel right to me.

    So what I did was I created a helpers/ directory at the root of my project and put the helper files inside of that, and in my composer.json file I did this:

    ...
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        },
        "files": [
            "helpers/ui_helpers.php"
        ]
    },
    ...
    

    This way my app/ directory is still a psr-4 autoloaded one, and the helpers are a little better organized.

    Hope this helps someone.

提交回复
热议问题