zablockibros/laravel-immutable

使模型属性不可变

dev-master 2019-03-04 19:21 UTC

This package is auto-updated.

Last update: 2024-09-05 19:27:15 UTC


README

使您的Laravel模型属性不可变...即当使用Eloquent更新记录后,不可变属性的值不会更改。

安装

要求:此包需要PHP 7.1.3或更高版本以及Laravel 5.7

$ composer require zablockibros/laravel-immutable

该包将自动注册其服务提供者。

定义不可变属性

在您的模型中定义要不可变的属性

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
use ZablockiBros\Immutable\Traits\HasImmutableAttributes;
 
class YourModel extends Model
{
    use HasImmutableAttributes;
    
    /**
     * @var array
     */
    protected $immutable = [
        'name',
        'sku',
    ];

在本例中,namesku 可以在模型创建时设置,然而,在更新时这些属性的值不会持久化更改到数据库中。

$model = new YourModel;
 
// set the attribute 
$model->name = 'test';
$model->name; // 'test'
 
// change it (pre-saving)
$model->name = 'changed';
$model->name; // 'changed'
 
// now we save the model
$model->save();
 
// can't change its value now
$model->name = 'nope';
$model->name; // 'changed'
 
// can't update it either
$model->save([
    'name' => 'nope',
]);
$model->name; // 'changed'

版权和许可

MIT许可.

版权(c)2019 Justin Zablocki