Skip to content

Instantly share code, notes, and snippets.

@danharper
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danharper/6dc1382ce828ad198024 to your computer and use it in GitHub Desktop.
Save danharper/6dc1382ce828ad198024 to your computer and use it in GitHub Desktop.
Simple Immutable Builder
<?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;
}
}
<?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