novocast / laravel-readonly
一个只读模型特质,用于辅助处理只读模型。
dev-master
2022-05-16 12:52 UTC
Requires
- php: >=7.0.0
This package is auto-updated.
Last update: 2024-09-16 17:55:09 UTC
README
简单特质
安装
composer require novocast/laravel-readonly
使用特质
非常简单。您只需添加特质。如果您尝试使用非只读方法,它将抛出异常。
<?php use Illuminate\Database\Eloquent\Model; use Novocast\ReadOnly\ReadOnlyTrait; class ReadOnlyModel extends Model { use ReadOnlyTrait; } $readme = new ReadOnlyModel(); /** * When calling this save method, the ReadOnlyExceptoin Exception * is thrown */ $readme->save();
如果您有一个可以和不可以保存到集合中的对象混合,您可以选择处理这个异常。考虑以下情况:
<?php use Illuminate\Database\Eloquent\Model; use Novocast\ReadOnly\ReadOnlyTrait; use Novocast\ReadOnly\ReadOnlyException; class ReadOnlyModel extends Model { use ReadOnlyTrait; } class RegularModel extends Model { // not using the read only trait } $models = []; for($count = 0; $count < 5; $count++) { if (mt_rand(0,100) > 50) { $models[] = new RegularModel(); } if (mt_rand(0,100) > 40) { $models[] = new ReadOnlyModel(); } } $collection = collect($models); foreach($models as $model) { try { $model->save(); } catch(ReadOnlyException $exception) { // This is a read only model. } } ?>