Last active
August 29, 2015 14:20
-
-
Save chukShirley/b5f87b2441ea7b6d6e04 to your computer and use it in GitHub Desktop.
Value Objects
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 | |
| namespace Sabel; | |
| class MyController | |
| { | |
| public function myMethod($data) | |
| { | |
| SysemReferenceNumberValue::fromString($data['systemReferenceNumber']); | |
| // Use SystemReferenceNumber value object from here on out | |
| } | |
| } |
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 | |
| namespace Sabel; | |
| use Sabel\AbstractValueInterface; | |
| class SystemReferenceNumberValue | |
| { | |
| private $value; | |
| private function __construct(){} | |
| public function getValue() | |
| { | |
| return $this->value; | |
| } | |
| // Use named constructors | |
| public static function fromString($string) | |
| { | |
| $number = new SystemReferenceNumberValue; | |
| $number->setValue($string); | |
| $number->filter()->validate(); | |
| return $number; | |
| } | |
| protected function filter() | |
| { | |
| $this->setValue(trim($this->value)); | |
| return $this; | |
| } | |
| private function validate() | |
| { | |
| // Ensure value is within allowed range | |
| if ($this->value <= 0) | |
| { | |
| throw new \InvalidArgumentException("System reference number must be a positive integer"); | |
| } | |
| elseif ($this->value > 999999999) | |
| { | |
| throw new \InvalidArgumentException("System reference number cannot be greater than 999999999"); | |
| } | |
| return $this; | |
| } | |
| private function setValue($value) | |
| { | |
| // Ensure value is an integer | |
| $this->value = (int) $value; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment