PHP code example of moonspot / value-objects

1. Go to this page and download the library: Download moonspot/value-objects library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

moonspot / value-objects example snippets




namespace Example;

use Moonspot\ValueObjects\ValueObject;

class Car extends ValueObject {

    public int $id = 0;

    public string $model = '';

    public string $make = '';


}

$car = new Car();
$car->fromArray(
    [
        'id'    => 1,
        'model' => 'Kia',
        'make'  => 'Sportage'
    ]
);

echo $car->toJSON();



namespace Example;

use Moonspot\ValueObjects\TypedArray;
use Moonspot\ValueObjects\ValueObject;

class CarSet extends TypedArray {
    public const REQUIRED_TYPE = [Car::class];
}

class Fleet extends ValueObject {
    public int $id = 0;

    public string $name = '';

    public CarSet $cars;

    public function __construct() {
        // Any properties which are ValueObjects or TypedArrays should be
        // initialized in the ValueObject's constructor
        $this->cars = new CarSet();
    }
}

$car = new Car();
$car->fromArray(
    [
        'id'    => 1,
        'model' => 'Kia',
        'make'  => 'Sportage'
    ]
);

$fleet = new Fleet();
$fleet->id = 1;
$fleet->name = "New Fleet";
$fleet->cars[] = $car;

echo $fleet->toJSON();



namespace Example;

use Moonspot\ValueObjects\ValueObject;
use Moonspot\ValueObjects\ArrayObject;

class Car extends ValueObject {

    public int $id = 0;

    public string $model = '';

    public string $make = '';

    public ArrayObject $attributes;

    public function __construct() {
        // Any properties which are ValueObjects or TypedArrays should be
        // initialized in the ValueObject's constructor
        $this->attributes = new ArrayObject();
    }
}

$car        = new Car();
$car->id    = 1;
$car->model = 'Kia';
$car->make  = 'Sportage';

$car->attributes['color'] = 'Blue';
$car->attributes['passengers'] = 5;
echo $car->toJSON();