hareland / laravel-immutable-attributes
使Laravel模型属性不可变
v1.0.2
2024-05-26 18:51 UTC
Requires
- php: ^8.1
- illuminate/database: ^8.0|^9.0|^10.0|^11.0|^12.0
- illuminate/support: ^8.0|^9.0|^10.0|^11.0|^12.0
Requires (Dev)
- mockery/mockery: ^1.0
- orchestra/testbench: ^7.10
- pestphp/pest: ^1.22
- pestphp/pest-plugin-laravel: ^1.3
- phpunit/phpunit: ^9.0
This package is auto-updated.
Last update: 2024-09-27 08:39:02 UTC
README
Laravel不可变模型属性
在您的Laravel模型上创建不可变属性。只需使用特性即可。
安装
要求:PHP 8.1+ 和 Laravel 8+
composer require hareland/laravel-immutable-attributes
定义不可变属性
在您的模型上定义要设置为不可变的属性
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Hareland\LaravelImmutableAttributes\Traits\HasImmutableAttributes; class Product extends Model { use HasImmutableAttributes; /** * @var array */ protected $immutable = [ 'label', 'price', ];
在这个例子中,label
和 price
可以在模型创建时设置,但是属性值在更新时不会持久化到数据库。
$model = new Product; // Set the attribute $model->label = 'abc'; $model->label; // 'abc' // Change it (before-saving) $model->label = 'abc'; $model->label; // 'abc' // Save it $model->save(); // You can't change its value $model->label = 'xyz'; $model->label; // 'abc' // You can't update it either $model->save([ 'label' => 'xyz', ]); $model->label; // 'abc'