Skip to content

Instantly share code, notes, and snippets.

@compwright
Created October 22, 2019 18:35
Show Gist options
  • Save compwright/f99a52326b3e159a1ec42d6a995a0d04 to your computer and use it in GitHub Desktop.
Save compwright/f99a52326b3e159a1ec42d6a995a0d04 to your computer and use it in GitHub Desktop.
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