Last active
August 29, 2015 14:14
-
-
Save danharper/6dc1382ce828ad198024 to your computer and use it in GitHub Desktop.
Simple Immutable Builder
This file contains 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 | |
abstract class Builder { | |
abstract function build(); | |
function __call($name, $arguments) | |
{ | |
if ( ! property_exists($this, $name)) | |
{ | |
throw new BadMethodCallException(sprintf('%s has no method "%s()"', __CLASS__, $name)); | |
} | |
if (count($arguments) !== 1) | |
{ | |
throw new InvalidArgumentException(sprintf('Only one argument must be provided to %s->%s()', __CLASS__, $name)); | |
} | |
$new = clone $this; | |
$new->$name = $arguments[0]; | |
return $new; | |
} | |
} |
This file contains 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 | |
final class PersonBuilder extends Builder { | |
protected $name; | |
protected $email; | |
protected $age; | |
function build() | |
{ | |
// validate properties, exception if invalid | |
// return a Person object | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment