Laravel-用于使用Blade渲染视图的大量访问器(Mutators)

问题描述 投票:3回答:1

我有一个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可以用于常规页面和管理页面(甚至更多)。

我也看了JsonResourceViewComposer,但JsonResource似乎是APIs的,而ViewComposer似乎特别是Views的。

我还考虑过为访问器添加acc_之类的前缀,以减少现有db列的错误:

public function getAccDisplayNameAttribute() { ... };

但是我真的不认为这是一个解决方案,我什至不确定我在做什么是对还是错。我也通过互联网搜索了最佳实践,但没有成功。

php laravel view model laravel-blade
1个回答
0
投票

为什么不只使用标准的PHP吸气剂?

© www.soinside.com 2019 - 2024. All rights reserved.