Download the PHP package esensi/model without Composer
On this page you can find all versions of the php package esensi/model. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package model
Esensi Model Traits Package
Version 1
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.
Note
This code is specifically designed to be compatible with the Laravel Framework and may not be compatible as a stand-alone dependency or as part of another framework.
Extend the Default Model
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:
Pro Tip: The more lean way to use
Esensi\Model
traits is to consume traits on the individual models instead of creating an inheritance dependency. Take a look at the generously commentedEsensi\Model\Model
source code for details on how to use individual traits with and without extending the default model.
Use Soft Deletes Instead
If the application requires that the articles be sent to the trash before permanently deleting them, then the developer can just swap out the Esensi\Model\Model
with the soft deleting version Esensi\Model\SoftModel
like so:
Pro Tip: While Laravel includes
SoftDeletingTrait
, Esensi expands upon this by also forcing the trait to comply with aSoftDeletingModelInterface
contract. This ensures a higher level of compatibility and code integrity. You can then do checks like$model instanceof SoftDeletingModelInterface
to conditionally handle actions.
Table of Contents
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.
- Installation
- Validating Model Trait
- Self-Taught Coders Tutorial
- Auto-Validating on Save
- Manually Validating Model Attributes
- Handling Validation Errors
- Using Force Save
- Purging Model Trait
- Auto-Purging on Save
- Manually Purging Model Attributes
- Hashing Model Trait
- Auto-Hashing on Save
- Manually Hashing Model Attributes
- Encrypting Model Trait
- Auto-Encrypting on Access
- Manually Encrypting Model Attributes
- Checking Encryption State
- Juggling Model Trait
- Auto-Juggling on Access
- Manually Juggling Model Attributes
- Soft Deleting Model Trait
- Using Soft Deletes
- Adding Custom Dates
- Using Force Delete
- Relating Model Trait
- Using Simplified Relationships
- Sluggable Model Trait
- Unit Testing
- Running the Unit Tests
- Contributing
- Licensing
Installation
Add the esensi/model
package as a dependency to the application. Using Composer, this can be done from the command line:
Or manually it can be added to the composer.json
file:
If manually adding the package, then be sure to run composer update
to update the dependencies.
Validating Model Trait
This package includes the ValidatingModelTrait
which implements the ValidatingModelInterface
on any Eloquent
model that uses it. The ValidatingModelTrait
adds methods to Eloquent
models for:
- Automatic validation on
create()
,update()
,save()
,delete()
, andrestore()
methods - Integration with Laravel's
Validation
services to validate model attributes - Integration with Laravel's
MessageBag
so that models can return errors when validation fails - Option to throw
ValidationException
when validation fails - Ability to
forceSave()
and bypass validation rules entirely - Automatic injection (or not) of the model's identifier for
unique
validation rules
Like 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.
Self-Taught Coders Tutorial
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.
- Read Laravel 8 Model Validation With the Esensi Model Traits Package
- Signup for From Ideas to Launch
Auto-Validating On Save
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.
Purging Model Trait
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:
- attributes in the
$purgeable
property - attributes prefixed with an underscore (i.e.:
_private
) - attributes ending in
_confirmation
(i.e.:password_confirmation
)
Like all the traits, it is self-contained and can be used individually.
Pro Tip: This trait uses the
PurgingModelObserver
to listen for theeloquent.creating
andeloquent.updating
events before automatically purging the purgeable attributes. The order in which the traits are used in theModel
determines the event priority: if using theValidatingModelTrait
be sure to use it first so that the purging event listner is fired after the validating event listener has fired.
Auto-Purging on Save
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.
Pro Tip: From an efficiency stand point, it is theoretically better to assign all purgeable attributes in the
$purgeable
property including underscore prefixed and_confirmation
suffixed attributes since the$purgeable
property is checked first and does not require string parsing and comparisons.
The developer can now pass form input to the Post
model from a controller or repository and the trait will automatically purge the non-attributes before saving. This gets around those pesky "Unknown column" MySQL errors when the set value is mutated to an internal attribute or when you conditionally want to ignore any fill values. For demonstrative purposes the following code shows this in practice from a simple route closure:
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.
Hashing Model Trait
This package includes the HashingModelTrait
which implements the HashingModelInterface
on any Eloquent
model that uses it. The HashingModelTrait
adds methods to Eloquent
models for automatically hashing attributes on the model just before write operations to the database. The trait includes the ability to:
- automatically hash attributes in the
$hashable
property - manually hash a value using the
hash()
method - compare a plain text value with a hash using the
checkHash()
method - check if a value is hashed using the
isHashed()
method - swap out the
HasherInterface
used using thesetHasher()
method
Like all the traits, it is self-contained and can be used individually.
Pro Tip: This trait uses the
HashingModelObserver
to listen for theeloquent.creating
andeloquent.updating
events before automatically hashing the hashable attributes. The order in which the traits are used in theModel
determines the event priority: if using theValidatingModelTrait
be sure to use it first so that the hashing event listner is fired after the validating event listener has fired.
Auto-Hashing on Save
While developers can of course use the Model
or SoftModel
classes which already include the HashingModelTrait
, the following code will demonstrate using automatic hashing on any Eloquent
based model. For this example, the implementation of automatic hashing will be applied to a User
model which requires the password to be hashed on save:
Pro Tip: The
HashingModelTrait
is a great combination for thePurgingModelTrait
. Often hashable attributes need to be confirmed and using thePurgingModelTrait
, the model can be automatically purged of the annoying_confirmation
attributes before writing to the database. While theuse
order of these two traits is not important relative to each other, it is important touse
them afterValidatingModelTrait
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 password
before saving. For demonstrative purposes the following code shows this in practice from a simple route closure:
Manually Hashing Model Attributes
It is also possible to manually hash attributes. The HashingModelTrait
includes several helper functions to make manual manipulation of the $hashable
property easier.
Encrypting Model Trait
This package includes the EncryptingModelTrait
which implements the EncryptingModelInterface
on any Eloquent
model that uses it. The EncryptingModelTrait
adds methods to Eloquent
models for automatically encrypting attributes on the model whenever they are set and for automatically decrypting attributes on the model whenever they are got. The trait includes the ability to:
- automatically encrypt attributes in the
$encryptable
property when setting them - automatically decrypt attributes in the
$encryptable
property when getting them - manually encrypt/decrypt a value using the
encrypt()
anddecrypt()
methods - check if a value is encrypted using the
isEncrypted()
method - swap out the encrypter class used using the
setEncrypter()
method
Like all the traits, it is self-contained and can be used individually. Be aware, however, that using this trait does overload the magic __get()
and __set()
methods of the model (see Esensi\Model\Model source code for how to deal with overloading conflicts).
Manually Encrypting Model Attributes
It is also possible to manually encrypt attributes. The EncryptingModelTrait
includes several helper functions to make manual manipulation of the $encryptable
property easier.
Juggling Model Trait
This package includes the JugglingModelTrait
which implements the JugglingModelInterface
on any Eloquent
model that uses it. The JugglingModelTrait
adds methods to Eloquent
models for automatically type casting (juggling) attributes on the model whenever they are got or set. The trait includes the ability to:
- automatically cast attributes to a type when getting them
- automatically cast attributes to a type when setting them
- manually casting a value using the
juggle()
method - manually casting to pre-defined types including:
null
=>juggleNull()
(returns null on empty)string
=>juggleString()
boolean
(bool
) =>juggleBoolean()
integer
(integer
) =>juggleInteger()
float
(double
) =>juggleFloat()
array
=>juggleArray()
date
=>juggleDate()
(returns Carbon date)datetime
(date_time
) =>juggleDateTime()
(returns as 0000-00-00 00:00:00)timestamp
=>juggleTimestamp()
(returns Unix timestamp)
- create custom types to cast to with magic model methods like:
- Example:
fooBar
=>juggleFooBar()
- Example:
Like all the traits, it is self-contained and can be used individually. Be aware, however, that using this trait does overload the magic __get()
and __set()
methods of the model (see Esensi\Model\Model source code for how to deal with overloading conflicts). Special credit goes to the brilliant Dayle Rees, author of Code Bright book, who inspired this trait with his pull request to Laravel which eventually arrived in Laravel 8 as Attribute Casting which supports basic type casting.
Auto-Juggling on Access
Pro Tip: PHP extensions like
php-mysqlnd
should be used when available to handle casting from and to persistent storage, this trait serves a dual purpose of type casting and simplified attribute mutation (juggling) especially when a native extension is not available.
While developers can of course use the Model
or SoftModel
classes which already include the JugglingModelTrait
, the following code will demonstrate using automatic type juggling on any Eloquent
based model. For this example, the implementation of automatic type juggling will be applied to a Post
model which requires certain attributes to be type casted when attributes are accessed:
The developer can now pass form input to the Post
model from a controller or repository and the trait will automatically type cast/juggle the attributes when setting. The same holds true for when the attributes are loaded from persistent storage as the model is constructed: the attributes are juggled to their types. Even for persistent storage that does not comply, the jugglable attributes are automatically type casted when retrieved from the model. For demonstrative purposes the following code shows this in practice from a simple route closure:
Pro Tip: Some great uses for
JugglingModelTrait
would be custom "types" that map to commonly mutators jugglers forphone
,url
,json
, types etc. Normally developers would have to map the attributes to attribute mutators and accessors which are hard-coded to the attribute name. Using the$jugglable
property these attributes can be mapped to custom juggle methods easily in a reusable way. Custom services could be used as part of the juggle method too. This would make converting currency from one type to a normalized type or to convert from floating values (1.99) to integers (199) when persisted.
Manually Juggling Model Attributes
It is also possible to manually juggle attributes. The JugglingModelTrait
includes several helper functions to make manual manipulation of the $jugglable
property easier.
Soft Deleting Model Trait
This package includes the SoftDeletingModelTrait
which implements the SoftDeletingModelInterface
on any Eloquent
model that uses it. The SoftDeletingModelTrait
wraps the default Eloquent
model's SoftDeletingTrait
for a unified naming convention and stronger interface hinting. The trait also includes the ability to set additional dates in the $dates
property without having to remember to add deleted_at
.
Like all the traits, it is self-contained and can be used individually. As a convenience, the Esensi\Model\SoftModel
extends the Esensi\Model\Model
and implements the trait already. The developer can just extend the SoftModel
and not have to refer to the Laravel soft deleting documentation again.
Pro Tip: Just because a model uses the
SoftDeletingModelTrait
does not mean that the database has thedeleted_at
column in its table. Be sure to add$table->softDeletes();
to a table migration.
Relating Model Trait
This package includes the RelatingModelTrait
which implements the RelatingModelInterface
on any Eloquent
model that uses it. The RelatingModelTrait
adds methods to Eloquent
models for automatically resolving related models:
- from simplified configs using the
$relationships
property - add pivot attributes from simplified configs using the
$relationshipPivots
property - as magic method calls such as
Post::find($id)->comments()->all()
- as magic attribute calls such as
Post::find($id)->author
Pro Tip: As an added bonus, this trait includes a special Eloquent
without()
scope which accepts relationships to remove from the eager loaded list, exactly opposite of the built in Eloquent support forwith()
. This is particularly useful for models that set the$with
property but occassionally need to remove the eager loading to improve performance on larger queries. This does not impact lazy/manual loading using the dynamic orload()
methods.
Like all the traits, it is self-contained and can be used individually. Be aware, however, that using this trait does overload the magic __call()
and __get()
methods of the model (see Esensi\Model\Model source code for how to deal with overloading conflicts). Special credit goes to Phillip Brown and his Philipbrown/Magniloquent Laravel package which inspired this trait.
Using Simplified Relationships
While developers can of course use the Model
or SoftModel
classes which already include the RelatingModelTrait
, the following code will demonstrate adding simplified relationship bindings to any Eloquent
based model.
The developer can now use the Post
model's relationships from a controller or repository and the trait will automatically resolve the relationship bindings. For demonstrative purposes the following code shows this pattern from a simple route closure:
Unit Testing
The Esensi platform includes other great packages just like this Esensi/Model package. This package is currently tagged as 1.x
because the other platform packages are not ready for public release. While the others may still be under development, this package already includes features that would be mature enough for a 1.x
release including unit testing and extensive testing in real-world applications.
Running the Unit Tests
This package uses PHPUnit to automate the code testing process. It is included as one of the development dependencies in the composer.json
file:
The test suite can be ran from the command line using the phpunit
test runner:
Important: There is currently a bug in Laravel (see issue #1181) that prevents model events from firing more than once in a test suite. This means that the first test that uses model tests will pass but any subseqeuent tests will fail. There are a couple of temporary solutions listed in that thread which you can use to make your tests pass in the meantime: namely
Model::flushEventListeners()
andModel::boot()
after each test runs.Pro Tip: Please help the open-source community by including good code test coverage with your pull requests. The Esensi development team will review pull requests with unit tests and passing tests as a priority. Significant code changes that do not include unit tests will not be merged.
Contributing
Thank you for considering contributing to Esensi Core!
Licensing
Copyright (c) 2022 SiteRocket Labs
Esensi Core is open-sourced software licensed under the MIT license.
All versions of model with dependencies
nesbot/carbon Version ^2.67
illuminate/contracts Version ^9.0|^10.0|^11.0
illuminate/database Version ^10.0
illuminate/encryption Version ^10.0
illuminate/events Version ^10.0
illuminate/hashing Version ^10.0
illuminate/support Version ^10.0
illuminate/validation Version ^10.0
paragonie/random_compat Version ^8.0|^9.0
symfony/polyfill-php81 Version ^1.23
watson/validating Version ^8.1