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
532 views
in Technique[技术] by (71.8m points)

php - Custom helper classes in Laravel 5.4

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 have a class CustomHelper that contains a method fooBar() :

<?php

nampespace AppHelpers;

class CustomHelper
{
    static function fooBar()
    {
        return 'it works!';
    }
}

I want to be able to do something like this in my blade templates:

{{ fooBar() }}

instead of doing this:

{{ AppHelpersCustomHelper::fooBar() }}

P.S: @andrew-brown's answer in Best practices for custom helpers on Laravel 5 deals with non-class files. It would be nice to have a class based solution so that the helper functions can be organized among classes.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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 appHelpershelpers.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 AppHelpersCustomHelper::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


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

...