2017 © Pedro Peláez
 

library value-object

Help to create immutable Value Objects

image

githubjeka/value-object

Help to create immutable Value Objects

  • Tuesday, January 26, 2016
  • by githubjeka
  • Repository
  • 1 Watchers
  • 3 Stars
  • 15 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 0 Forks
  • 0 Open issues
  • 2 Versions
  • 7 % Grown

The README.md

Trait Value Object

Help to create immutable Value Objects, (*1)

Build Status, (*2)

Default API

Two methods compareTo and changeTo:, (*3)

// Value Object is a Metre(['1', 'centimeter'])
$metre = new Metre(['1', 'cm']);
$metre->compareTo([2,'cm']); // returns -1
$metre->compareTo([.1,'m']); // returns 0
$metre->compareTo([1,'mm']); // returns 1
$metre->changeTo([1,'m']) //returns new  Metre(['1', 'm']), $metre is  Metre(['1', 'centimeter'])

//user API via changeTo
$metre->toMillimeter(); // new Metre(['10', 'mm']), $metre is  Metre(['1', 'centimeter'])
$metre->toMillimeter()->add([1,'mm'])->getAmount();  //returns 11

// rewrite __toString()
echo $metre // returns '1'

a little more

final class Money
{
    use ImmutableValueObject;

    private $amount;
    private $currency;

    protected function compare($valueObject)
    {
        return bccomp($this->toUsd()->amount, $valueObject->toUsd()->amount);
    }

    protected function setAttributes($value)
    {
        // ... validate value

        $this->currency = $value[1];
        $this->amount = $value[0];
    }

    private function getCurrencies()
    {
        return [
            'usd' => 1,
            'rub' => 60,
            //...
        ];
    }

    public function toUsd()
    {
        if ($this->currency === 'usd') {
            return $this->changeTo([$this->amount, 'usd']);
        }        
        $k = $this->getCurrencies()[$this->currency];
        return $this->changeTo([$this->amount * $k, 'usd']);
    }

    public function toRub()
    {            
        $amount = $this->toUsd()->amount;
        $k = $this->getCurrencies()['rub'];
        return $this->changeTo([$amount / $k, 'rub']);
    }
}

The Versions

26/01 2016

dev-master

9999999-dev https://github.com/githubjeka/value-object

Help to create immutable Value Objects

  Sources   Download

MIT

The Requires

  • php >=5.4.0

 

immutable value objects

25/01 2016

v1.0.0

1.0.0.0 https://github.com/githubjeka/value-object

Help to create immutable Value Objects

  Sources   Download

MIT

The Requires

  • php >=5.4.0

 

immutable value objects