-
-
Save devmsh/c4d7085089da87593d133accedef4a16 to your computer and use it in GitHub Desktop.
IoC implementation
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 | |
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) | |
{ | |
$reflection = new ReflectionClass($className); | |
$constructor = $reflection->getConstructor(); | |
if ($constructor && count($constructor->getParameters())) { | |
$args = array_map(function ($param) { | |
return Container::make($param->getClass()->name); | |
}, $constructor->getParameters()); | |
return $reflection->newInstanceArgs($args); | |
} else { | |
return new $className(); | |
} | |
} | |
} | |
$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