PHP code example of slepic / value-object

1. Go to this page and download the library: Download slepic/value-object 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/ */

    

slepic / value-object example snippets


final class StringIsEmpty extends Violation
{
  public function __construct(string $message = '')
  {
    parent::__construct($message ?: 'Value cannot be empty');
  }
}

class NonEmptyString
{
  private string $value;

  public function __construct(string $value)
  {
    if ($value === '') {
      throw ViolationException::for(new StringIsEmpty());
    }
    $this->value = $value;
  }

  public function __toString(): string
  {
    return $this->value;
  }
}

final class FullName
{
  public NonEmptyString $firstName;
  public NonEmptyString $surname;

  public function __construct(NonEmptyString $firstName, NonEmptyString $surname)
  {
    $this->firstName = $firstName;
    $this->surname = $surname;
  }
}

class MyValueObject
{
  private string $x;
  private int $y;

  public function __construct(string $x, int $y)
  {
    $this->x = $x;
    $this->y = $y;
  }

  public static function fromArray(array $data): self
  {
    return FromArrayConstructor::constructFromArray(static::class, $data);
  }

  public function with(array $data): self
  {
    return FromArrayConstructor::combineWithArray($this, $data);
  }

  public functin toArray(): array
  {
    return FromArrayConstructor::extractConstructorArguments($this);
  }
}

$vo = MyValueObject::fromArray([
  'x' => 'test',
  'y' => 10,
]);

$vo2 = $vo->with(['y' => $vo->y + 1]);

class MyStructure extends DataStructure
{
  private NonEmptyString $name;
  private PositiveInteger $age;

  public function __construct(NonEmptyString $name, PositiveInteger $age)
  {
    $this->name = $name;
    $this->age = $age;
  }

  public function getName(): NonEmptyString
  {
    return $this->name;
  }

  public function getAge(): PositiveInteger
  {
    return $this->age;
  }
}

// automatically construct from array, potentialy using upcasting/downcasting
$vo = MyStructure::fromArray([
  'name' => 'Slim Shady',
  'age' => 18,
]);

// automatic withers with upcasting/downcasting ability
$vo2 = $vo->with(['age' => 19]);

// automatic to array conversion
echo \json_encode($vo2->toArray()); // {"name": "Slim Shady", "age": 19}

$vo->with(['name' => '']); // throws ViolationExceptionInterface