Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.