If you intend to use builder pattern in your project (see article on Wikipedia) you can use a prototype implementation of builder pattern from this library.
In order to do so, you have to create your own builder class, extend
RunOpenCode\AbstractBuilder\AbstractBuilder
and implement methods
configureParameters
and getObjectFqcn
.
For those extra lazy developers, there is a
RunOpenCode\AbstractBuilder\ReflectiveAbstractBuilder
as well, which
implements configureParameters
method by introspecting constructor parameters
and default values.
NOTE: Builder class MUST NOT validate provided parameters. Class which ought to be builded must do such validation, because construction process of any instance of any class must be valid whether is executed with or without builder implementation.
Let's say that we have some class Message
for which we have to provide
a builder class. Here is how to do so:
<?php
class Message
{
private $id;
private $message;
private $timestamp;
public function __construct($id, $message, $timestamp)
{
$this->id = $id;
$this->message = $message;
$this->timestamp = $timestamp;
}
}
final class MessageBuilder extends \RunOpenCode\AbstractBuilder\AbstractBuilder
{
/**
* Get builded message.
*
* Alias to \RunOpenCode\AbstractBuilder\AbstractBuilder::build() method.
*
* @see \RunOpenCode\AbstractBuilder\AbstractBuilder::build()
*
* @return object
*/
public function getMessage()
{
return $this->build();
}
/**
* {@inheritdoc}
*/
protected function configureParameters()
{
return array(
'id' => null,
'message' => null,
'timestamp' => new \DateTime('now')
);
}
/**
* {@inheritdoc}
*/
protected function getObjectFqcn()
{
return Message::class;
}
}
Start with creating a builder, you can use plain constructor:
$builder = new MessageBuilder();
or you can use a static method for that:
$builder = MessageBuilder::create();
You can get/set each individual configured builder property via:
Property access:
$builder->id = 1;
$id = $builder->id;
Setter method:
$builder->setId(1);
$id = $builder->getId();
Array access:
$builder['id'] = 1;
$id = $builder['id'];
Multiple properties, via array:
$builder->fromArray([ 'id' => 1, 'message' => 'Some message' ]);
$allProperties = $builder->toArray();
$someProperties = $builder->toArray([ 'id', 'message' ]);
And finaly, you can build conrete object by calling build()
method, or
invoking builder as method:
$message = $builder->build();
$message = $builder();
Fluent interface is supported for setter methods, so you can chain them, example:
$message = MessageBuilder::create()
->setId(1)
->setMessage('Some message')
->setTimestamp(new \DateTime('now'))
->build();