Laravel 5.4 中的自定义辅助类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43168719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Custom helper classes in Laravel 5.4
提问by byteseeker
I have some helper classes in app/Helpers
. How do I load these classes using a service provider
to use them in blade templates?
我在app/Helpers
. 如何使用 a 加载这些类service provider
以在刀片模板中使用它们?
e.g. If I have a class CustomHelper
that contains a method fooBar()
:
例如,如果我有一个CustomHelper
包含方法的类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() }}
instead of doing this:
而不是这样做:
{{ \App\Helpers\CustomHelper::fooBar() }}
P.S:@andrew-brown's answerin Best practices for custom helpers on Laravel 5deals with non-class files. It would be nice to have a class based solution so that the helper functions can be organized among classes.
PS:@安德鲁-布朗的回答中的最佳做法上Laravel 5个自定义的助手与非类文件的交易。最好有一个基于类的解决方案,以便可以在类之间组织辅助函数。
回答by Marcin Nabia?ek
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.
我认为当你的类中有代码时,不可能只使用函数。好吧,您可以尝试扩展 Blade,但这太多了。
What you should do is creating one extra file, for example app\Helpers\helpers.php
and in your composer.json file put:
你应该做的是创建一个额外的文件,例如app\Helpers\helpers.php
,在你的 composer.json 文件中放置:
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\": "app/"
},
"files": ["app/Helpers/helpers.php"] // <- this line was added
},
create app/Helpers/helpers.php
file and run
创建app/Helpers/helpers.php
文件并运行
composer dump-autoload
Now in your app/Helpers/helpers.php
file you could add those custom functions for example like this:
现在在您的app/Helpers/helpers.php
文件中,您可以添加这些自定义函数,例如:
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:
顺便说一句,这正是 Laravel 为它自己的助手所做的,例如:
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
如您所见array_add
,只是更短(或可能不那么冗长)的写作方式Arr::add