Created
September 3, 2015 08:03
-
-
Save prigazzi/b7c441b6968a3e889816 to your computer and use it in GitHub Desktop.
A Simple Deferred Object implementation.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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]; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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."; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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