Package Data | |
---|---|
Maintainer Username: | redcrystalcode |
Maintainer Contact: | szainmehdi@gmail.com (Zain Mehdi) |
Package Create Date: | 2015-11-22 |
Package Last Update: | 2015-12-06 |
Language: | PHP |
License: | MIT |
Last Refreshed: | 2024-11-19 03:10:24 |
Package Statistics | |
---|---|
Total Downloads: | 22,141 |
Monthly Downloads: | 32 |
Daily Downloads: | 2 |
Total Stars: | 23 |
Total Watchers: | 7 |
Total Forks: | 0 |
Total Open Issues: | 1 |
Cast your Eloquent model attributes to value objects with ease!
This package requires PHP >= 5.4. Using the latest version of PHP is highly recommended. Laravel 4.x and 5.x are supported.
Note: Running tests for this package requires PHP >=5.6.
Require this package with composer using the following command:
composer require redcrystal/cast
This package lets you easily cast your model attributes to Value Objects that implement our RedCrystal\Cast\ValueObject
interface. A simple example is provided below.
<?php
namespace App\ValueObjects;
use RedCrystal\Cast\ValueObject;
class Email implements ValueObject
{
protected $value;
public function __construct($value)
{
$this->value = $value;
}
public function toScalar()
{
return $this->value;
}
public function __toString() {
return $this->toScalar();
}
}
Set up your model by using the included Trait
and adding a tiny bit of configuration.
<?php
namespace App;
use App\ValueObjects\Email;
use Illuminate\Database\Eloquent\Model;
use RedCrystal\Cast\CastsValueObjects;
class User extends extends Model {
use CastsValueObjects;
protected $objects = [
// name of the attribute => name of the value object class
'email' => Email::class
];
// ...
}
When accessing attributes of your model normally, any attribute you've set up for casting will be returned as an instance of the Value Object.
$user = User::find($id);
$user->email; // returns instance of App\ValueObjects\Email
$user->email->toScalar(); // "someone@example.com"
(string) $user->email; // "someone@example.com"
You can set an attribute set up for casting with either a scalar (native) value, or an instance of the Value Object.
$user = new User();
$user->email = "someone@example.com";
$user->email = new Email("someone@example.com");
This package is open-source software licensed under the MIT license.