timmcleod/laravel-view-model

此包已被弃用且不再维护。未建议替代包。

Laravel 5.x 的视图模型

v1.0.4 2016-06-12 17:52 UTC

This package is auto-updated.

Last update: 2024-02-24 06:54:16 UTC


README

使用视图模型清理混乱的视图

此包可以帮助您封装、验证和操作Laravel 5.x应用程序中每个视图所需的数据。

目的和概述

随着我们应用程序中视图的日益复杂,它们往往需要以不同方式呈现的更多数据。随着我们的视图依赖性增加和视图文件变得更加复杂,跟踪视图所需数据的难度越来越大。

视图模型通过以下方式帮助

  • 验证注入到视图中的数据,以验证数据是否与视图预期完全一致。
  • 促进将数据与在视图上下文中操作数据所需的方法捆绑在一起。
  • 降低在视图中无意中覆盖“全局”变量的可能性。
  • 提供一种方法,可以一目了然地查看视图所需的数据。

安装

使用composer安装此包

composer require timmcleod/laravel-view-model

然后,在您的应用程序配置(project/config/app.php)中将以下服务提供者注册到providers数组中

'providers' => [
    ...
    TimMcLeod\InstanceValidator\InstanceValidatorServiceProvider::class,
    TimMcLeod\ViewModel\ViewModelServiceProvider::class,
]

入门

注册ViewModelServiceProvider后,将可用一个新Artisan命令来生成您的视图模型。要创建新的视图模型,请使用make:view-model Artisan命令

php artisan make:view-model EditProfileViewModel

此命令将在您的app/Http/ViewModels目录中放置一个新的EditProfileViewModel类。如果该目录不存在,它将为您创建。

<?php

namespace App\Http\ViewModels;

use TimMcLeod\ViewModel\BaseViewModel;

class EditProfileViewModel extends BaseViewModel
{
    /** @var array */
    protected $rules = [];
}

如果您希望对视图模型进行分组,您可以使用这种方式生成它们

php artisan make:view-model User/EditProfileViewModel

此命令将在您的app/Http/ViewModels/User目录中放置一个新的EditProfileViewModel类。

基本用法

要使用视图模型,只需创建视图模型的新实例,并将实例传递到视图中。

$vm = new EditProfileViewModel([
    'timezones' => Timezone::all(),
    'states'    => State::all(),
    'cities'    => City::all(),
    'user'      => Auth::user()
]);

return view('user.profile')->with('vm', $vm);

在实例化新的视图模型时,将使用您在视图模型类中定义的规则验证数据。您可以使用Laravel文档中定义的任何可用验证规则

还有三个额外的规则可供使用: instance_ofcollection_ofpaginator_of

protected $rules = [
    'timezones' => 'required|collection_of:App\\Timezone',
    'states'    => 'required|collection_of:App\\State',
    'cities'    => 'present|collection_of:App\\City',
    'user'      => 'required|instance_of:App\\User',
];

如果来自控制器的任何数据验证失败,将抛出异常。

在您的视图中,您可以通过这种方式访问视图模型中的数据: $vm->timezones

您还可以向视图模型添加自己的方法,以将视图特定的逻辑与数据捆绑在一起,以保持视图整洁。

// Inside of EditProfileViewModel class:

/**
 * Returns true if the user's timezone is the same as the given timezone.
 *
 * @param Timezone $timezone
 * @return bool
 */
public function isSelectedTimezone(Timezone $timezone)
{
    return $this->user->timezone === $timezone->code;
}
<!-- Inside of user.profile view -->

<select id="timezone" name="timezone">
    @foreach($vm->timezones as $timezone)
        <option value="{{$timezone->code}}" {{$vm->isSelectedTimezone($timezone) ? 'selected' : ''}}>{{$timezone->label}}</option>
    @endforeach
</select>

或者,也许您想在特定视图中创建两个列中城市的复选框列表。您可以这样操作

// Inside of EditProfileViewModel class:

/**
 * Returns the first half of cities from the cities array.
 *
 * @return array
 */
public function citiesCol1()
{
    $len = count($this->cities);
    return $this->cities->slice(0, round($len / 2));
}

/**
 * Returns the second half of cities from the cities array.
 *
 * @return array
 */
public function citiesCol2()
{
    $len = count($this->cities);
    return $this->cities->slice(round($len / 2));
}
<!-- Inside of user.profile view -->

<!-- Inside markup for column 1 -->
@foreach($vm->citiesCol1() as $city)
    <label><input name="cities[]" type="checkbox" value="{{$city->id}}">{{"$city->name, $city->state_code"}}</label>
@endforeach
    
<!-- Inside markup for column 2 -->
@foreach($vm->citiesCol2() as $city)
    <label><input name="cities[]" type="checkbox" value="{{$city->id}}"> {{"$city->name, $city->state_code"}}</label>
@endforeach

如您所见,视图模型允许我们将视图数据与其在视图上下文中操作数据的所需方法捆绑在一起。

许可证

Laravel的视图模型是开源软件,许可证为MIT许可证

Laravel是Taylor Otwell的商标。