timmcleod / laravel-core-lib
Laravel 的库
Requires
- php: >=7.3
- illuminate/filesystem: ^7.0
- illuminate/support: ^7.0
- ramsey/uuid: ~3.0
Requires (Dev)
- orchestra/testbench: ^5.0
- phpunit/phpunit: ^8.5
README
安装
此包需要 PHP >= 7.3。使用 composer 安装此包
composer require timmcleod/laravel-core-lib
然后,在您的应用程序配置(project/config/app.php
)中注册以下服务提供者,将它们添加到 providers
数组中
'providers' => [ TimMcLeod\LaravelCoreLib\Providers\LaravelCoreLibServiceProvider::class, TimMcLeod\LaravelCoreLib\Providers\LaravelCoreLibArtisanServiceProvider::class, ]
跟踪可追踪模型
跟踪 Eloquent 模型中发生的变化
此特性的目的是让我们能够跟踪 Eloquent 模型中属性值的变化,以便我们可以在模型保存后访问这些变化。
如果我们想要将更改记录下来以供以后审查,这可能会很有用。
要跟踪对 Eloquent 模型的属性/字段所做的更改,只需将 ChangeTrackable
特性添加到要跟踪的模型中。如果您想限制跟踪哪些字段,只需添加一个名为 $trackable
的属性,如下所示。
use Illuminate\Database\Eloquent\Model; use TimMcLeod\LaravelCoreLib\Database\Eloquent\ChangeTrackable; class User extends Model { use ChangeTrackable; protected $trackable = ['first_name', 'last_name']; }
当您的模型保存时,ChangeTrackable
特性将自动跟踪已更改的字段。以下方法可用于了解这些更改
/** * Returns true if any of the $trackable attributes have changed. If the * $trackable property evaluates as empty, this will return true if * any of the attributes' values have changed on the model. * * @return bool */ $model->hasTrackedChanges() /** * Returns a string representation of the attributes that have changed. If a * property called $trackable exists on the model, then that $trackable * array is used to filter the attributes that should be serialized. * * If the $trackable property doesn't exist on the model or evaluates as empty, * then all of the tracked changes will be serialized without being filtered. * * @param string $format * @param string $delimiter * @param string $emptyOld * @param string $emptyNew * @return string */ $model->getTrackedChanges($format = '{attribute}: {old} > {new}', $delimiter = ' | ', $emptyOld = '', $emptyNew = '') /** * Returns an array of the attributes that have changed. If a property called * $trackable exists on the model, then the $trackable array will be used * to limit or filter the attributes that are returned in the result. * * If the $trackable property doesn't exist on the model or evaluates as empty, * then all of the tracked changes will be returned without being filtered. * * @return array */ $model->getTrackedChangesArray() /** * Returns true if any of the given attributes have changed on the model, * regardless of whether or not the $trackable property is defined on * the model. * * @param array $attributes * @return bool */ $model->hasAnyTrackedChangesFor($attributes = []) /** * Returns a string representation of the attributes that have changed. If the * $attributes parameter evaluates as empty, then all tracked changes will * be serialized into a string without being filtered. * * @param array $attributes * @param string $format * @param string $delimiter * @param string $emptyOld * @param string $emptyNew * @return string */ $model->getTrackedChangesFor($attributes = [], $format = '{attribute}: {old} > {new}', $delimiter = ' | ', $emptyOld = '', $emptyNew = '') /** * Returns an array of the attributes that have changed. If the $attributes * parameter evaluates as empty, then all tracked changes are returned. * * @param array $attributes * @return array */ $model->getTrackedChangesArrayFor($attributes = []) /** * Returns true if any of the model's attributes have changed, regardless * of whether or not the $trackable property is defined on the model. * * @return bool */ $model->hasAnyTrackedChanges() /** * Returns a string representation of ALL of the attributes that have changed * on the model, even if the $trackable property does exist on the model. * * @param string $format * @param string $delimiter * @param string $emptyOld * @param string $emptyNew * @return string */ $model->getTrackedChangesForAll($format = '{attribute}: {old} > {new}', $delimiter = ' | ', $emptyOld = '', $emptyNew = '') /** * Returns an array of the attributes that have changed. If the $trackable * property exists on the model, it's ignored, and all tracked changes * are always returned, regardless of whether $trackable exists. * * @return array */ $model->getTrackedChangesArrayForAll()
视图模型
使用视图模型清理混乱的视图
此包可以帮助您封装、验证和操作 Laravel 5.x 应用程序中每个视图所需的数据。
目的和概述
随着我们应用程序中的视图变得更加复杂,它们往往需要以不同方式呈现的数据更多。随着视图依赖关系的增加和视图文件的复杂化,跟踪视图所需的数据可能变得越来越困难。
视图模型通过以下方式帮助
- 验证注入到视图中的数据,以验证数据是否正是视图所期望的。
- 简化将数据与在视图上下文中操作数据的所需方法捆绑在一起。
- 降低在视图内部意外覆盖“全局”变量的可能性。
- 提供一种方法,可以一目了然地看到视图需要哪些数据。
入门
在您注册了 LaravelCoreLibArtisanServiceProvider
之后,将出现一个新的 Artisan 命令,用于生成视图模型。要创建新的视图模型,请使用 make:view-model
Artisan 命令
php artisan make:view-model EditProfileViewModel
此命令将在您的 app/Http/ViewModels
目录中创建一个新的 EditProfileViewModel
类。如果该目录不存在,系统会为您创建。
<?php namespace App\Http\ViewModels; use TimMcLeod\LaravelCoreLib\View\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);
在您的视图中,您可以像这样访问视图模型中的数据:$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 文档中定义的任何 可用的验证规则。
protected $rules = [ 'total' => 'required|integer', 'name' => 'required|string', ];
如果来自控制器的数据有任何验证失败,将抛出一个异常。
< 小贴士 >
可选地,如果您需要 timmcleod/laravel-instance-validator
包,它将添加一些额外的验证规则,这些规则在您想要验证视图模型接收的数据时可能很有用。
这些规则在 timmcleod/laravel-instance-validator
中可用:instance_of
、collection_of
和 paginator_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', ];
< /小贴士 >
可保存文件模型
待办:编写有关与模型一起保存文件的有用信息
ICS 日历
待办:编写有关使用 ICS 文件创建日历事件的有用信息
许可证
LaravelCoreLib for Laravel 是开源软件,受 MIT 许可证 许可。
Laravel 是 Taylor Otwell 的商标。