Skip to content

Instantly share code, notes, and snippets.

@vasilake-v
Created June 28, 2018 09:28
Show Gist options
  • Save vasilake-v/a72c70d28a0caae0baac3280de7488dc to your computer and use it in GitHub Desktop.
Save vasilake-v/a72c70d28a0caae0baac3280de7488dc to your computer and use it in GitHub Desktop.
Class that allows to initialize a object like with a builder factory that will fill in new object property values.
<?php
/**
* Created by PhpStorm.
* User: Veaceslav Vasilache <[email protected]>
* Date: 6/14/18
* Time: 1:14 PM
*/
namespace TinAppBundle\Infrastructure;
/**
* Class Chainable
*
* It behaves as a builder factory that will fill in new object properties.
*
* Example:
* class Font {
* public $name;
* public $size;
* public $weight;
* }
*
* $font = Chainable::create(Font::class)
* ('name', 'Tahoma Regular')
* ('size', 10)
* ('weight', 100)
* ->get();
*
*/
final class Chainable
{
private $newObj;
private function __construct($newObj)
{
$this->newObj=$newObj;
}
public static function create(string $newObjectClass)
{
if (!class_exists($newObjectClass)){
throw new \Exception('Class doesn\'t exist');
}
return new self(new $newObjectClass());
}
/**
* @param $property
* @param $value
*
* @return $this
*/
public function __invoke($property, $value)
{
$this->newObj->{$property} = $value;
return $this;
}
public function get()
{
return $this->newObj;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment