我有一个Laravel 7项目,在显示之前,需要从模型到视图的大量数据转换。
我曾考虑过使用Laravel Accessors,并直接在我的blade.php文件中使用它们。但是,当我处理完一个简单的html表时,我看了看我的代码,我认为访问器太多了,甚至其中一些访问器的名字都很难读。
@foreach($races as $race)
<tr>
<td>{{ $race->display_dates }}</td>
<td>{{ $race->display_name }}</td>
<td>{{ $race->type->name }}</td>
<td>{{ $race->display_price }}</td>
<td>{{ $race->display_places }}</td>
<td>{{ $race->online_registration_is_open ? 'Yes' : 'No' }}</td>
</tr>
@endforeach
public function show(Group $group)
{
$races = $group->races;
$races->loadMissing('type'); // Eager loading
return view('races', compact('races'));
}
// Accessors
public function getOnlineRegistrationIsOpenAttribute()
{
if (!$this->online_registration_ends_at && !$this->online_registration_starts_at) return false;
if ($this->online_registration_ends_at < now()) return false;
if ($this->online_registration_starts_at > now()) return false;
return true;
}
public function getNumberOfParticipantsAttribute()
{
return $this->in_team === true
? $this->teams()->count()
: $this->participants()->count();
}
// Accessors mainly used for displaying purpose
public function getDisplayPlacesAttribute()
{
if ($this->online_registration_ends_at < now()) {
return "Closed registration";
}
if ($this->online_registration_starts_at > now()) {
return "Opening date: " . $this->online_registration_starts_at;
}
return "$this->number_of_participants / $this->max_participants";
}
public function getDisplayPriceAttribute()
{
$text = $this->online_registration_price / 100;
$text .= " €";
return $text;
}
public function getDisplayDatesAttribute()
{
$text = $this->starts_at->toDateString();
if ($this->ends_at) { $text .= " - " . $this->ends_at->toDateString(); }
return $text;
}
public function getDisplayNameAttribute()
{
$text = $this->name;
if ($this->length) { $text .= " $this->length m"; }
if ($this->elevation) { $text .= " ($this->elevation m)"; }
return $text;
}
此代码有效,但我认为它有很多缺点:例如,如果我在此处创建name
访问器时关联的数据库表具有getDisplayNameAttribute
列,则可能会引起可读性和错误。这只是一个开始,我想我需要其他视图增加30-40个访问器...另外,我将需要多次使用其中的一些,例如getDisplayNameAttribute
可以用于常规页面和管理页面(甚至更多)。
我也看了JsonResource和ViewComposer,但JsonResource
似乎是APIs
的,而ViewComposer
似乎特别是Views
的。
我还考虑过为访问器添加acc_
之类的前缀,以减少现有db列的错误:
public function getAccDisplayNameAttribute() { ... };
但是我真的不认为这是一个解决方案,我什至不确定我在做什么是对还是错。我也通过互联网搜索了最佳实践,但没有成功。
为什么不只使用标准的PHP吸气剂?