Skip to content

Instantly share code, notes, and snippets.

@akramabdulrahman
Last active June 19, 2017 11:59
Show Gist options
  • Save akramabdulrahman/12b541fb0bb1ea6da989e3c1c72062e6 to your computer and use it in GitHub Desktop.
Save akramabdulrahman/12b541fb0bb1ea6da989e3c1c72062e6 to your computer and use it in GitHub Desktop.
possible di implmentation
<?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