Skip to content

Instantly share code, notes, and snippets.

@chrispage1
Last active August 20, 2025 15:51
Show Gist options
  • Select an option

  • Save chrispage1/d253ee496fdfa383d8070bdc327b35f1 to your computer and use it in GitHub Desktop.

Select an option

Save chrispage1/d253ee496fdfa383d8070bdc327b35f1 to your computer and use it in GitHub Desktop.
An example of how dependency injection works
<?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