Laravel 5.4中的自定义帮助程序类 [英] Custom helper classes in Laravel 5.4

查看:97
本文介绍了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 App\Helpers;

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

我希望能够在刀片模板中执行以下操作:

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

{{ fooBar() }}

而不是这样做:

{{ \App\Helpers\CustomHelper::fooBar() }}

PS:: answer /stackoverflow.com/questions/28290332/best-practices-for-custom-helpers-on-laravel-5">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.

您应该做的是创建一个额外的文件,例如app\Helpers\helpers.php,并在composer.json文件中放置:

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

创建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 \App\Helpers\CustomHelper::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

这篇关于Laravel 5.4中的自定义帮助程序类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆