The base model traits of Esensi
Version 3
An Esensi package, coded by SiteRocket Labs®.
The Esensi/Model package is just one package that makes up Esensi, a platform built on Laravel. This package uses PHP traits to extend Laravel's default Eloquent models and traits. Using traits allows for a high-degree of code reusability and extensibility. While this package provides some reasonable base models, developers are free to mix and match traits in any combination needed, being confident that the code complies to a reliable interface and is properly unit tested. For more details on the inner workings of the traits please consult the generously documented source code.
This code is specifically designed to be compatible with the Laravel Framework ^10 and may not be compatible as a stand-alone dependency or as part of another framework.
The simplest way to demonstrate the traits is to extend the base Esensi\Model\Model. For example, if the application requires a simple blog, then the developer could create a Post model that automatically handles validation, purging, hashing, encrypting, attribute type juggling and even simplified relationship bindings by simply extending this ready-to-go model:
…
php
Pro Tip: While Laravel includes SoftDeletingTrait, Esensi expands upon this by also forcing the trait to comply with a SoftDeletingModelInterface contract. This ensures a higher level of compatibility and code integrity. You can then do checks like $model instanceof SoftDeletingModelInterface to conditionally handle actions.
Help Write Better Documentation: The documentation is still a work in progress. You can help others learn to reuse code by contributing better documentation as a pull request.
Add the esensi/model package as a dependency to the application. Using Composer, this can be done from the command line:
composer require esensi/model
Or manually it can be added to the composer.json file:
{
"require": {
"esensi/model": "^3.0"
}
}
If manually adding the package, then be sure to run composer update to update the dependencies.
This package includes the ValidatingModelTrait which implements the ValidatingModelInterface on any Eloquent model that uses it. The ValidatingModelTrait adds methods to Eloquent models for:
create(), update(), save(), delete(), and restore() methodsValidation services to validate model attributesMessageBag so that models can return errors when validation failsValidationException when validation failsforceSave() and bypass validation rules entirelyunique validation rulesLike all the traits, it is self-contained and can be used individually. Special credit goes to the very talented Dwight Watson and his Watson/Validating Laravel package which is the basis for this trait. Emerson Media collaborated with him as he created the package. Esensi wraps his traits with consistent naming conventions for the other Esensi model traits. Please review his package in detail to see the inner workings.
This Esensi package has been featured in various places from university classrooms to coding schools to online programming courses. Among one of those online programming courses is Alex Coleman's Self-Taught Coders series From Idea To Launch. Throughout the course, Alex teaches how to design and build a complete Laravel web application. Lesson 24 in the series covers automatic model validation using Esensi\Model as a basis for the workflow. According to Alex:
Model validation is the method of establishing rules to ensure when you’re creating, or updating, an object based on a model, that all of its field values are set appropriately. That all required fields are filled, that all date fields are formatted properly, etc.
While developers can of course use the Model or SoftModel classes which already include the ValidatingModelTrait, the following code will demonstrate adding auto-validation to any Eloquent based model.
…
Then from the controller or repository the developer can interact with the Post model's attributes, call the save() method and let the Post model handle validation automatically. For demonstrative purposes the following code shows this pattern from a simple route closure:
…
Calling the save() method on the newly created Post model would instead use the "updating" ruleset from Post::$ruleset while saving. If that ruleset did not exist then it would default to using the Post::$rules.
Pro Tip: While using this pattern is perfectly fine, try not to actually validate your form requests using such rulesets. Instead use Laravel 8's FormRequest injection to validate your forms. The ValidatingModelTrait is for validating your model's data integrity, not your entry form validation.
This package includes the PurgingModelTrait which implements the PurgingModelInterface on any Eloquent model that uses it. The PurgingModelTrait adds methods to Eloquent models for automatically purging attributes from the model just before write operations to the database. The trait automatically purges:
$purgeable property_private)_confirmation (i.e.: password_confirmation)Like all the traits, it is self-contained and can be used individually.
Pro Tip: This trait uses the
PurgingModelObserverto listen for theeloquent.creatingandeloquent.updatingevents before automatically purging the purgeable attributes. The order in which the traits are used in theModeldetermines the event priority: if using theValidatingModelTraitbe sure to use it first so that the purging event listner is fired after the validating event listener has fired.
While developers can of course use the Model or SoftModel classes which already include the PurgingModelTrait, the following code will demonstrate using automatic purging on any Eloquent based model.
…
php Route::post( 'posts', function( $id ) { // Hydrate the model from the Input $input = Input::all(); $post = new Post($input);
// At this point $post->analytics_id might exist.
// If we tried to save it, MySQL would throw an error.
// Save the Post
$post->save();
// At this point $post->analytics_id is for sure purged.
// It was excluded becaused it existed in Post::$purgeable.
});
### Manually Purging Model Attributes
It is also possible to manually purge attributes. The `PurgingModelTrait` includes several helper functions to make manual manipulation of the `$purgeable` property easier.
```php
// Hydrate the model from the Input
$post = Post::find($id);
$post->fill( Input::all() );
// Manually purge attributes prior to save()
$post->purgeAttributes();
// Manually get the attributes
$post->getHashable(); // ['foo']
// Manually set the purgeable attributes
$post->setPurgeable( ['foo', 'bar'] ); // ['foo', 'bar']
// Manually add an attribute to the purgeable attributes
$post->addPurgeable( 'baz' ); // ['foo', 'bar', 'baz']
$post->mergePurgeable( ['zip'] ); // ['foo', 'bar', 'baz', 'zip']
$post->removePurgeable( 'foo' ); // ['bar', 'baz', 'zip']
// Check if an attribute is in the Post::$purgeable property
if ( $post->isPurgeable( 'foo' ) )
{
// ... foo is not purgeable so this would not get executed
}
// Do not run purging for this save only.
// This is useful when purging is enabled
// but needs to be temporarily bypassed.
$post->saveWithoutPurging();
// Disable purging
$post->setPurging(false); // a value of true would enable it
// Run purging for this save only.
// This is useful when purging is disabled
// but needs to be temporarily ran while saving.
$post->saveWithPurging();
…
php
**Pro Tip:** The `HashingModelTrait` is a great combination for the `PurgingModelTrait`. Often hashable attributes need to be confirmed and using the `PurgingModelTrait`, the model can be automatically purged of the annoying `_confirmation` attributes before writing to the database. While the `use` order of these two traits is not important relative to each other, it is important to `use` them after `ValidatingModelTrait` if that trait is used as well. Otherwise, the model will purge or hash the attributes before validating.
The developer can now pass form input to the `User` model from a controller or repository and the trait will automatically hash the `passwo
No open issues yet, or sync has not completed.