Laravel 5.4 中的自定义助手类

我在 app/Helpers 中有一些帮助程序类.如何使用 service provider 加载这些类以在刀片模板中使用它们?

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

例如如果我有一个包含方法 fooBar() 的类 CustomHelper :

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() }}

而不是这样做:

{{ AppHelpersCustomHelper::fooBar() }}

PS: @andrew-brown 的 答案 在 Laravel 5 上自定义助手的最佳实践处理非类文件.最好有一个基于类的解决方案,以便可以在类之间组织辅助函数.

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.

推荐答案

当你的类中有代码时,我认为不可能只使用函数.好吧,您可以尝试扩展 Blade,但它太多了.

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.

你应该做的是创建一个额外的文件,例如 appHelpershelpers.php 并在你的 composer.json 文件中放置:

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

创建 app/Helpers/helpers.php 文件并运行

composer dump-autoload

现在在您的 app/Helpers/helpers.php 文件中,您可以添加这些自定义函数,例如:

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.

顺便说一句,这正是 Laravel 为它自己的助手所做的,例如:

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);
    }
}

如您所见,array_add 只是更短(或者可能不太冗长)的编写方式 Arr::add

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

相关文章