Skip to content

Instantly share code, notes, and snippets.

@dimabory
Last active January 31, 2019 14:31
Show Gist options
  • Save dimabory/84b5e29aeb31a2be119c3fa13aa83f0c to your computer and use it in GitHub Desktop.
Save dimabory/84b5e29aeb31a2be119c3fa13aa83f0c to your computer and use it in GitHub Desktop.
VO, DTO
VO DTO
Data yes yes
Logic yes no
Identity no no
Immutability yes no

VO

final class Address
{
    private $street;
    private $unit;
    private $room;

    public function __construct(string $street, int $unit, ?int $room = null)
    {
        $this->street = $street;
        $this->unit   = $this->handleNumberArgument($unit);
        $this->room   = $room ? $this->handleNumberArgument($room) : null;
    }
    
    public function assignRoom(int $room): self
    {
        if (null !== $this->room) {
            throw new LogicException('The room is already assigned to this address');
        }

        return new self($this->street, $this->unit, $room);
    }

    public function __toString(): string
    {
        return implode(',', [$this->street, $this->unit, $this->room ?? '']);
    }

    private function handleNumberArgument($value): int
    {
        if ($value <= 0) {
            throw new InvalidArgumentException('Number must be more than \'0\'');
        }

        return $value;
    }
}

DTO

final class UserRegisterRequest
{
    public const PASSWORD_MIN_LENGTH = 6;

    public $username;
    public $password;

    private function __construct(string $username, string $password)
    {
        $this->username = $username;
        $this->assertPasswordLength($password);
        $this->password = $password;
    }

    public static function create(string $username, string $password): self
    {
        return new self($username, $password);
    }

    private function assertPasswordLength(string $password)
    {
        if (self::PASSWORD_MIN_LENGTH >= strlen($password)) {
            throw new InvalidArgumentException('Password must be more than 6 characters.');
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment