Last active
August 20, 2025 15:51
-
-
Save chrispage1/d253ee496fdfa383d8070bdc327b35f1 to your computer and use it in GitHub Desktop.
An example of how dependency injection works
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 | |
| // create our service container | |
| $serviceContainer = [ | |
| TestClass::class => new TestClass('Matt') | |
| ]; | |
| // create our test class | |
| class TestClass { | |
| public function __construct(string $name) | |
| { | |
| $this->name = $name; | |
| } | |
| public function welcome(): string | |
| { | |
| return sprintf('Hey there %s', $this->name); | |
| } | |
| } | |
| // create our class that uses dependency injection | |
| class Controller { | |
| public function index(TestClass $class) | |
| { | |
| echo 'Hey there ' . $class->name; | |
| } | |
| } | |
| // create our injection method. This will work out anything our | |
| // classes need to run | |
| $run = function ($class, $method) use ($serviceContainer) { | |
| // build an array of items to inject | |
| $inject = []; | |
| // inspect our class using reflection, find the method | |
| // we're looking for and get the parameters we are looking for | |
| $reflection = new ReflectionClass($class); | |
| $reflectionMethod = $reflection->getMethod($method); | |
| $reflectionParameters = $reflectionMethod->getParameters(); | |
| // loop through each parameter and see if we can get it from our service container. | |
| foreach ($reflectionParameters as $parameter) { | |
| // if we have a class that we're looking for within our service container, | |
| // add it to our array of injected parameters | |
| if (array_key_exists($parameter->getType()->getName(), $serviceContainer)) { | |
| $inject[$parameter->getName()] = $serviceContainer[$parameter->getType()->getName()]; | |
| } | |
| } | |
| // create our class and run our method with our new parameters | |
| return (new $class)->{$method}(...$inject); | |
| }; | |
| // call our run method | |
| $run(Controller::class, 'index'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment