I'd like to instantiate multiple (i.e. of the same type) different (i.e. differing combination of attributes) complex (i.e. many optional parameters) objects in my code.
I think that using a Builder as described by Joshua Bloch here and talked about over here is the best way to go.
A very basic implementation would look like this:
class ObjectBuilder implements ObjectBuilderInterface
{
public function setAttributeA( $value ) : self
{
$this->attributeA = $value;
return $this;
}
public function setAttributeB( $value ) : self
{
$this->attributeB = $value;
return $this;
}
.
.
.
public function build() : Object
{
return new Object ($this->attributeA, $this->attributeB,...);
}
}
BUT as far as I understand the inner workings of a builder, by using the setters on the builder object the builder itself has a state and couldn't be reused for another object without unsetting all attributes first.
A use case for example in a controller would look something like this:
public function FooController (ObjectBuilderInterface $builder, ...)
{
$builder
->setAttributeA('A')
->setAttributeB('B');
$instance1 = $builder->build();
$builder
->setAttributeA('C')
->setAttributeB('D');
$instance2 = $builder->build();
}
One could make an unset call at the end of build()
but that feels somewhat wrong to me and in my above mentioned sources aswell as everywhere I looked for a real life implementation of such a builder (I live in Symfony-land and had a look into FormBuilder for example) was anything like an unset()
used.
How is a Builder used to instantiate multiple different instances?