| 1 |
<?php |
| 2 |
|
| 3 |
require __DIR__ . '/../vendor/autoload.php'; |
| 4 |
|
| 5 |
class Dough {} |
| 6 |
class Cheese {} |
| 7 |
class Slice {} |
| 8 |
class Pizza { |
| 9 |
function __construct($style, Cheese $cheese) {} |
| 10 |
function setDough(Dough $dough) {} |
| 11 |
function getSlice() { return new Slice(); } |
| 12 |
} |
| 13 |
class CheeseFactory { |
| 14 |
static function getCheese() { return new Cheese(); } |
| 15 |
} |
| 16 |
|
| 17 |
/** |
| 18 |
* @property-read string $style |
| 19 |
* @property-read Dough $dough |
| 20 |
* @property-read Cheese $cheese |
| 21 |
* @property-read Pizza $pizza |
| 22 |
* @method Slice new_slice() |
| 23 |
*/ |
| 24 |
class MyDI extends \Props\Container { |
| 25 |
public function __construct() { |
| 26 |
$this->style = 'deluxe'; |
| 27 |
|
| 28 |
$this->dough = function (MyContainer $c) { |
| 29 |
return new Dough(); |
| 30 |
}; |
| 31 |
|
| 32 |
$this->setFactory('cheese', 'CheeseFactory::getCheese'); |
| 33 |
|
| 34 |
$this->pizza = function (MyContainer $c) { |
| 35 |
$pizza = new Pizza($c->style, $c->cheese); |
| 36 |
$pizza->setDough($c->dough); |
| 37 |
return $pizza; |
| 38 |
}; |
| 39 |
|
| 40 |
// note 3rd argument $shared is false |
| 41 |
$this->slice = function (MyContainer $c) { |
| 42 |
return $c->pizza->getSlice(); |
| 43 |
}; |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
$c = new MyContainer; |
| 48 |
|
| 49 |
// You can request dependencies in any order. They're resolved as needed. |
| 50 |
|
| 51 |
$slice1 = $c->new_slice(); // This first resolves and caches the cheese, dough, and pizza. |
| 52 |
$slice2 = $c->new_slice(); // This just gets a new slice from the existing pizza. |
| 53 |
|
| 54 |
assert($slice1 !== $slice2); |
| 55 |
assert($c->pizza === $c->pizza); |
| 56 |
|