Last active
June 19, 2017 11:59
-
-
Save akramabdulrahman/12b541fb0bb1ea6da989e3c1c72062e6 to your computer and use it in GitHub Desktop.
possible di implmentation
This file contains 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 | |
require '../vendor/autoload.php'; | |
class B | |
{ | |
public $name = 'akram'; | |
} | |
class A | |
{ | |
private $b; | |
public function getB() | |
{ | |
return $this->b; | |
} | |
function __construct(B $b) | |
{ | |
$this->b = $b; | |
} | |
} | |
class Container | |
{ | |
public static function make($className) | |
{ | |
$class = new ReflectionClass($className); | |
$constructor = $class->getConstructor(); | |
if (!$constructor || ($constructor && count($constructor->getParameters()) == 0)) { | |
$obj = new $className; | |
} else { | |
$_params = collect($constructor->getParameters()) | |
->reduce(function ($acc, $item) { | |
$acc[] = Container::make($item->getClass()->name); | |
return $acc; | |
}, []); | |
$obj = $class->newInstanceArgs($_params); | |
} | |
return $obj; | |
} | |
} | |
$b = Container::make(B::class); // no problem | |
$a = Container::make(A::class); // Too few arguments exception | |
var_dump($a->getB()); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment