【发布时间】:2020-08-23 01:28:26
【问题描述】:
我有一个 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 getter?
-
抱歉,我需要说明为什么我应该使用 getter 或其他东西,以及为什么它更好。
-
虽然 JsonResource 是为 API 设计的,但是这个概念可以起到类似的作用。您只需要像 DTO(数据传输对象)一样拥有它,它可以调解您的数据(模型)和响应。如果访问器很少,则可以使用访问器,但如果这些逻辑专用于其他类来处理,则绝对是可维护的。
标签: php laravel view model laravel-blade