Last active
September 26, 2019 18:02
-
-
Save JasonTheAdams/544c5baac97bede5fd8669c8b1c1d1b9 to your computer and use it in GitHub Desktop.
Example of the Value Object Design Pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Temperature | |
{ | |
const KELVIN = 'kelvin'; | |
const FAHRENHEIT = 'fahrenheit'; | |
const CELSIUS = 'celsius'; | |
private $unit; | |
private $value; | |
public static function units() | |
{ | |
return [ | |
self::KELVIN, | |
self::FAHRENHEIT, | |
self::CELSIUS | |
]; | |
} | |
public function __construct($value, string $unit = self::FAHRENHEIT) | |
{ | |
if (! in_array($unit, self::units())) { | |
throw new InvalidArgumentException( | |
"Invalid temperature unit: $unit. Must be one of: " . join(', ', self::units()) | |
); | |
} | |
if (! is_numeric($value)) { | |
throw new InvalidArgumentException("Invalid temperature value, must be numeric: $value"); | |
} | |
$this->unit = $unit; | |
$this->value = (float)$value; | |
} | |
public function celsiusValue() | |
{ | |
switch ($this->unit) { | |
case self::CELSIUS: | |
return $this->value; | |
case self::KELVIN: | |
return $this->value - 273.15; | |
case self::FAHRENHEIT: | |
return ($this->value - 32) * 5 / 9; | |
} | |
} | |
public function fahrenheitValue() | |
{ | |
if (self::FAHRENHEIT === $this->unit) { | |
return $this->value; | |
} | |
return ($this->celsiusValue() * 9 / 5) + 32; | |
} | |
public function kelvinValue() | |
{ | |
if (self::KELVIN === $this->unit) { | |
return $this->value; | |
} | |
return $this->celsiusValue() + 273.15; | |
} | |
public function equals(Temperature $temperature) | |
{ | |
return $this->celsiusValue() === $temperature->celsiusValue(); | |
} | |
public function isGreaterThan(Temperature $temperature) | |
{ | |
return $this->celsiusValue() > $temperature->celsiusValue(); | |
} | |
public function isLessThan(Temperature $temperature) | |
{ | |
return $this->celsiusValue() < $temperature->celsiusValue(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment