https://github.com/githubjeka/value-object
Help to create immutable Value Objects
https://github.com/githubjeka/value-object
Last synced: 5 months ago
JSON representation
Help to create immutable Value Objects
- Host: GitHub
- URL: https://github.com/githubjeka/value-object
- Owner: githubjeka
- Created: 2016-01-25T08:41:08.000Z (almost 10 years ago)
- Default Branch: master
- Last Pushed: 2016-01-26T05:35:38.000Z (almost 10 years ago)
- Last Synced: 2025-07-28T05:51:18.942Z (6 months ago)
- Language: PHP
- Size: 7.81 KB
- Stars: 2
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Trait Value Object
Help to create immutable Value Objects
[](https://travis-ci.org/githubjeka/value-object)
## Default API
Two methods [`compareTo`](https://github.com/githubjeka/value-object/blob/master/src/ImmutableValueObject.php#L64-L86)
and [`changeTo`](https://github.com/githubjeka/value-object/blob/master/src/ImmutableValueObject.php#L64-L86):
```php
// 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
```php
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']);
}
}
```