Created
October 22, 2019 18:35
-
-
Save compwright/f99a52326b3e159a1ec42d6a995a0d04 to your computer and use it in GitHub Desktop.
PHP Dependency Injection in <10 lines
This file contains hidden or 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 | |
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