Download the PHP package waavi/laravel-value-objects without Composer
On this page you can find all versions of the php package waavi/laravel-value-objects. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download waavi/laravel-value-objects
More information about waavi/laravel-value-objects
Files in waavi/laravel-value-objects
Package laravel-value-objects
Short Description Value Objects for Laravel 5.1
License MIT
Informations about the package laravel-value-objects
Value Objects for Laravel 5
Allows you to create value objects in Eloquent Models that are then saved into the database as either plain strings or json encoded.
WAAVI is a web development studio based in Madrid, Spain. You can learn more about us at waavi.com
Installation
You may install the package via composer
composer require waavi/laravel-value-objects 1.0.x
Usage
Using single field value objects
Say you wish to add an Temperature field to a Device eloquent model. You may wish to apply transformations to this field, or get the value in Celsius, Fahrenheit or Kelvin. If you use this type of field in several models, it might become cumbersome to copy paste these functions between all models.
Here is were value objects become very useful. Let's see how. First we created the Device model, which will have a temperature field cast to the Temperature value object and will use the 'CastsValueObjects' trait.
The Temperature value object will extend from 'Waavi\ValueObjects\Single' and could be defined as follows:
Single field value objects are saved as plain string in the database, and can be uses as follows:
You may also use Accessors and Mutators, just like in Eloquent Models. For example you could rewrite the Temperature class as:
You could then access the temperature properties as follows:
Using multiple fields value objects
Sometimes are value objects might not be so simple, and might require several fields instead of just one. Let's say we have a Trip model with origin and destination fields made up of coordinates. We could then define the Trip model like we did before:
We would then be able to define the Coordinate value object like:
Now we need to extend from the 'Waavi\ValueObjects\Json' Value Object, since we will need several fields to represent our Value Object, and we will need to define a fillable array with the names of the fields that are allowed in the value object. This time, the field will be json encoded before being saved.
As before, mutators and accessors are available.
We can work with this model object like so:
All versions of laravel-value-objects with dependencies
illuminate/cache Version 5.1.x
illuminate/http Version 5.1.x