在 php Laravel 5 中创建自定义辅助函数的最佳实践是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30804201/
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
What is the best practice to create a custom helper function in php Laravel 5?
提问by cyber8200
I have
我有
the default created_atdate keep printing out as an MySQL format : 2015-06-12 09:01:26. I wanted to print it as my own way like 12/2/2017
, and other formats in the future.
默认的created_at日期继续打印为 MySQL 格式:2015-06-12 09:01:26。我想以我自己的方式打印它,就像12/2/2017
未来的其他格式一样。
I created
我创建
a file called DataHelper.php
and store it at /app/Helpers/DateHelper.php
- and it looks like this
一个名为的文件DataHelper.php
并将其存储在/app/Helpers/DateHelper.php
- 它看起来像这样
<?php
namespace App\Helpers;
class DateHelper {
public static function dateFormat1($date) {
if ($date) {
$dt = new DateTime($date);
return $dt->format("m/d/y"); // 10/27/2014
}
}
}
I want
我想要
to be able to called it in my blade view like
能够在我的刀片视图中调用它
DateHelper::dateFormat1($user->created_at)
I'm not sure what to do next.
我不知道接下来要做什么。
What is the best practice to create a custom helper function in php Laravel 5?
在 php Laravel 5 中创建自定义辅助函数的最佳实践是什么?
采纳答案by cyber8200
- Within your
app/Http
directory, create ahelpers.php
file and add your functions. - Within
composer.json
, in theautoload
block, add"files": ["app/Http/helpers.php"]
. - Run
composer dump-autoload
- 在您的
app/Http
目录中,创建一个helpers.php
文件并添加您的函数。 - 在 中
composer.json
,在autoload
块中,添加"files": ["app/Http/helpers.php"]
。 - 跑
composer dump-autoload
That should do it. :)
那应该这样做。:)
回答by Emeka Mbah
Since your Helper method is static you could add your helper class to config/app
alias just like a Facade, like so:
由于您的 Helper 方法是静态的,您可以config/app
像 Facade 一样将您的 helper 类添加到别名,如下所示:
'aliases' => [
//'dateHelper'=> 'App\Helpers\DateHelper', //for Laravel 5.0
'dateHelper'=> App\Helpers\DateHelper::class, //for Laravel 5.1
]
Then later in your view:
然后在你看来:
{{dateHelper::dateFormat1($user->created_at)}}
However, if you are also looking for a way to do this without a helper class. You may consider using Mutators and Appends in your model:
但是,如果您也在寻找一种没有帮助类的方法来做到这一点。您可以考虑在模型中使用 Mutators 和 Appends:
class User extends Model{
protected $fillable = [
'date'
];
protected $appends = [
'date_format_two'
];
public function getDateAttribute($value){
$dt = new DateTime($value);
return $dt->format("m/d/y"); // 10/27/2014
}
//date
public function getDateFormatTwoAttribute($value){
$dt = new DateTime($value);
return $this->attributes['date_format_two'] = $dt->format("m, d ,y"); // 10,27,2014
}
}
Later you can do
以后你可以做
$user = User::find(1);
{{$user->date}};
{{$user->date_format_two}};