Implementing Dependency Injection in PHP
A quick introduction to how PHP frameworks implement dependency injection using reflection.
Zach Robichaud
Table of Contents
Quick Notes on Implementing Dependency Injection
Most PHP frameworks use dependency injection to automatically supply function parameters. This reduces redundant code by eliminating the need to manually instantiate classes everywhere they're needed.
Basic Example
Consider this simple class structure:
class User {
public $id = 1;
}
class Test {
public static function test(User $user) {
return $user->id;
}
}
The test method requires a User object. With dependency injection, the framework automatically provides it.
How It Works: PHP Reflection
Here's a basic example of how to implement this using PHP's Reflection API:
$controller = 'Test';
$method = 'test';
$rm = new ReflectionMethod($controller, $method);
$parameters = [];
foreach ($rm->getParameters() as $parameter) {
// Get the expected class for this parameter
$class_name = $parameter->getType()->getName();
// Instantiate and add to parameters array
$parameters[] = new $class_name;
}
// Call the method with the resolved parameters
call_user_func_array([$controller, $method], $parameters);
The framework uses reflection to inspect the method signature, determine what parameters are expected, and automatically instantiate the required objects.
This is a simplified example—real implementations handle much more, including constructor injection, interface bindings, and singleton patterns.
Resources
How was this article?
Related Posts
Decluttering Your Laravel Console: How to Hide Artisan Commands
Laravel ships with over 100 built-in Artisan commands, making it hard to find your custom commands in the noise. Learn how to create a clean, focused command list that only shows what your team actually uses—while keeping all commands fully functional.
How Automated SSL Enhances Your Site's Protection
The Tiny Padlock That Protects Your Entire Website - Why SSL/TLS, Automation, and Certificate Management Matter More Than Ever.
If Searching for Quotes Breaks Your Software
When entering a single or double quote crashes your application, you likely have a SQL injection vulnerability. Here's what to do about it.
Comments (0)
No comments yet. Be the first to share your thoughts!