Laravel 5.4中的自定义帮助程序类 [英] Custom helper classes in 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::
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屋!