Package Data | |
---|---|
Maintainer Username: | davidmpeace |
Maintainer Contact: | peaceman@gmail.com (David Peace) |
Package Create Date: | 2016-04-14 |
Package Last Update: | 2019-10-21 |
Home Page: | |
Language: | PHP |
License: | MIT |
Last Refreshed: | 2024-11-08 03:24:43 |
Package Statistics | |
---|---|
Total Downloads: | 20,472 |
Monthly Downloads: | 0 |
Daily Downloads: | 0 |
Total Stars: | 6 |
Total Watchers: | 1 |
Total Forks: | 4 |
Total Open Issues: | 1 |
Immutability is a simple package that is used in your Eloquent models to enforce attribute immutability. Immutable attributes may be set, and changed once, but once the model is saved, the value can not be changed.
Immutability is open-sourced software licensed under the MIT license
To get started with Immutability, add to your composer.json
file as a dependency:
composer require davidmpeace/immutability
To use the Immutability library, you simply need to use the Immutability trait for any model you wish to identify immutable attributes for. Typically, you would want to implement the trait in your super-class so that all your sub-classes will automatically inherit the functionality.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Eloquent\Attributes\Immutability;
class MyAppSuperModel extends Model
{
use Immutability;
protected $immutable = ['id', 'uuid'];
}
Class override.
<?php
namespace App;
class User extends MyAppSuperModel
{
protected $immutable = ['id', 'uuid', 'username'];
}
Catching exceptions
<?php
namespace App;
use Eloquent\Attributes\Exceptions\ImmutableFieldViolationException;
use Exception;
$user = User::find(1);
try {
$user->username = "myNewUserName";
$user->save();
} catch ( ImmutableFieldViolationException $e ) {
// Handle immutable attribute violation error
} catch ( Exception $e ) {
// Handle error
}