为Laravel Eloquent模型提供辅助方法的最佳位置在哪里?
目前我正在创建BaseModel
,扩展Eloquent
并在其中添加额外的功能。然后我的所有模型都延伸BaseModel
。它有效..但它感觉不对。
例如,目前是我的BaseModel ......
class BaseModel extends Eloquent {
protected static function getEnumValues($table, $field)
{
$test=DB::select(DB::raw("show columns from {$table} where field = '{$field}'"));
preg_match('/^enum\((.*)\)$/', $test[0]->Type, $matches);
foreach( explode(',', $matches[1]) as $value )
{
$enum[] = trim( $value, "'" );
}
return $enum;
}
protected static function convertDate($date)
{
if(!isset($date)) return;
$new_date = DateTime::createFromFormat('d/m/Y', $date);
$formated_date = $new_date->format('Y-m-d');
return $formated_date;
}
}
我在我的模特中使用它们......
public static function boot()
{
parent::boot();
static::creating(function($campaign)
{
$campaign->sale_date = static::convertDate($campaign->sale_date);
$campaign->sold_date = static::convertDate($campaign->sold_date);
});
}
放置这样的模型助手方法的最佳位置在哪里?
反馈意见,谢谢!
答案 0 :(得分:1)
您可以编写一个静态助手类,然后从模型中调用它。 您可以参考my blog post了解如何添加自定义类。或者你总是可以使用psr-0或psr-4
来使用composer autoload答案 1 :(得分:0)
我所做的是...我在其中创建了一个 Helper Directory,并在其中创建了一个 GlobalHelper.php 文件。
tnow=datetime.datetime.now()
date_string = tnow.strftime('%Y-%m-%d')
print(f"datestring ={date_string}")
timeIntervals=["09:15:00","09:45:00","10:15:00","10:45:00","11:15:00","11:45:00","12:15:00","12:45:00","01:15:00","01:45:00","02:15:00","02:45:00","03:15:00","03:30:00"]
DatetimeIntervals=[]
now=datetime.datetime.now()
current_date=now.date()
for timeinterval in timeIntervals:
DatetimeIntervals.append(datetime.datetime.strptime(date_string+' '+timeinterval,"%Y-%m-%d %H:%M:%S"))
print(timeinterval)
for i,timeint in enumerate(DatetimeIntervals):
print(timeint)
for i,timeint in enumerate(DatetimeIntervals):
nexttime=timeint[i+1]
while(datetime.datetime.now()>timeint and datetime.datetime.now()<nexttime):
#here check if trade is active or not.
time.sleep(2)
在 GlobalHelper.php 中
app/Helper/GlobalHelper.php
比在控制器或任何地方这样调用:
namespace App\Helper;
use App\Command;
class GlobalHelper{
public static function getCommands(){
$getCommands = Command::all();
return $getCommands;
}
}