Custom helper classes in Laravel 5.4

后端 未结 1 1636
面向向阳花
面向向阳花 2021-01-08 00:17

I have some helper classes in app/Helpers. How do I load these classes using a service provider to use them in blade templates?

e.g. If I h

相关标签:
1条回答
  • 2021-01-08 00:51

    I don't think it's possible to use only function when you have code in your classes. Well, you could try with extending Blade but it's too much.

    What you should do is creating one extra file, for example app\Helpers\helpers.php and in your composer.json file put:

    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        },
        "files": ["app/Helpers/helpers.php"] // <- this line was added
    },
    

    create app/Helpers/helpers.php file and run

    composer dump-autoload
    

    Now in your app/Helpers/helpers.php file you could add those custom functions for example like this:

    if (! function_exists('fooBar')) {
       function fooBar() 
       {
          return \App\Helpers\CustomHelper::fooBar();
       }
    }
    

    so you define global functions but in fact all of them might use specific public methods from some classes.

    By the way this is exactly what Laravel does for its own helpers for example:

    if (! function_exists('array_add')) {
        function array_add($array, $key, $value)
        {
            return Arr::add($array, $key, $value);
        }
    }
    

    as you see array_add is only shorter (or maybe less verbose) way of writing Arr::add

    0 讨论(0)
提交回复
热议问题