| 1 |
<?php |
| 2 |
|
| 3 |
require __DIR__ . '/../vendor/autoload.php'; |
| 4 |
|
| 5 |
class AAA {} |
| 6 |
class BBB {} |
| 7 |
class CCC { |
| 8 |
public function __construct(BBB $bbb) {} |
| 9 |
public function setBbb(BBB $bbb) {} |
| 10 |
public $aaa; |
| 11 |
} |
| 12 |
class DDD {} |
| 13 |
function get_a_bbb() { return new BBB; } |
| 14 |
|
| 15 |
/** |
| 16 |
* @property-read AAA $aaa |
| 17 |
* @property-read BBB $bbb1 |
| 18 |
* @property-read BBB $bbb2 |
| 19 |
* @property-read BBB $bbb3 |
| 20 |
* @property-read CCC $ccc |
| 21 |
* @property-read DDD $ddd |
| 22 |
* |
| 23 |
* @method AAA new_aaa() |
| 24 |
*/ |
| 25 |
class MyContainer extends \Props\Container { |
| 26 |
public function __construct() { |
| 27 |
// store plain old values |
| 28 |
$this->ddd = new DDD; |
| 29 |
$this->{'bbb.class'} = 'BBB'; |
| 30 |
|
| 31 |
// set a factory, which will construct an object on demand |
| 32 |
$this->aaa = function () { |
| 33 |
return new AAA(); |
| 34 |
}; |
| 35 |
|
| 36 |
// alternative factory syntax, and using a reference to specify the class name |
| 37 |
$this->setFactory('bbb1', function (MyContainer $c) { |
| 38 |
return new $c->{'bbb.class'}; |
| 39 |
}); |
| 40 |
|
| 41 |
// fetch with a callback |
| 42 |
$this->setFactory('bbb2', 'get_a_bbb'); |
| 43 |
|
| 44 |
// Closures automatically used as factories |
| 45 |
$this->bbb3 = function (MyContainer $c) { |
| 46 |
return $c->bbb2; |
| 47 |
}; |
| 48 |
|
| 49 |
// more advanced factory |
| 50 |
$this->ccc = function (MyContainer $c) { |
| 51 |
$val = new CCC($c->bbb1); |
| 52 |
$val->setBbb($c->bbb2); |
| 53 |
$val->aaa = $c->aaa; |
| 54 |
return $val; |
| 55 |
}; |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
$c = new MyContainer; |
| 60 |
|
| 61 |
$c->aaa; // factory builds a AAA |
| 62 |
$c->aaa; // the same AAA |
| 63 |
$c->new_aaa(); // always a freshly-built AAA |
| 64 |
|
| 65 |
$c->bbb1; // factory resolves bar.class, builds a BBB |
| 66 |
$c->bbb2; // invoker calls get_a_bbb() |
| 67 |
$c->bbb3; // invoker executes anon func, returning the already-cached $c->bbb2 instance |
| 68 |
|
| 69 |
$c->ccc; // factory creates CCC, passing a new BBB object, |
| 70 |
// calls setBbb(), passing in $c->bbb2, |
| 71 |
// and sets the aaa property to $c->aaa |
| 72 |
|