Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PHP Dependency Injection in <10 lines
<?php
function inject (array $container, $class, $method) {
extract($container);
$args = array_map(
function (ReflectionParameter $arg) {
return $arg->getName();
},
(new ReflectionMethod($class, $method))->getParameters()
);
return compact($args);
}
class A {
public static function foo(B $b) {}
public static function bar(C $c, B $b) {}
}
class B {}
class C {}
$container = [
'b' => new B(),
'c' => new C()
];
call_user_func_array(['A', 'foo'], inject($container, 'A', 'foo'));
// calls A::foo($b);
call_user_func_array(['A', 'bar'], inject($container, 'A', 'bar'));
// calls A::bar($c, $b);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.