Skip to content

Instantly share code, notes, and snippets.

@prigazzi
Created September 3, 2015 08:03
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 prigazzi/b7c441b6968a3e889816 to your computer and use it in GitHub Desktop.
Save prigazzi/b7c441b6968a3e889816 to your computer and use it in GitHub Desktop.
A Simple Deferred Object implementation.
<?php
class Builder
{
public $objects = [];
public $factory = [];
public function factory($name, $callable)
{
$this->factory[$name] = $callable->bindTo($this);
}
public function &defer($name) {
$args = array_slice(func_get_args(), 1);
$this->objects[$name] = new Deferred($this, $name, $args);
return $this->objects[$name];
}
public function get($name, $arguments = []) {
$this->objects[$name] = call_user_func_array($this->factory[$name], $arguments);
return $this->objects[$name];
}
}
<?php
class Deferred
{
public function __construct(&$builder, $name, $arguments)
{
$this->name = $name;
$this->arguments = $arguments;
$this->builder = $builder;
}
public function __call($name, $arguments)
{
$real = $this->builder->get($this->name, $this->arguments);
return call_user_func_array([$real, $name], $arguments);
}
public function __get($name)
{
$real = $this->builder->get($this->name, $this->arguments);
return $real->$name;
}
}
<?php
class Real
{
public function __construct($one, $two)
{
$this->one = $one;
$this->two = $two;
}
public function execute()
{
return "$this->one plus $this->two is something.";
}
}
<?php
$builder = new Builder();
$builder->factory("Real", function($first, $second) {
return new Real($first, $second);
});
$deferred = &$builder->defer("Real", "One", "Two");
var_dump($deferred->two);
var_dump($deferred);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment