Implementing Dependency Injection in PHP
Technology February 1, 2018 1 min read 384 views

Implementing Dependency Injection in PHP

A quick introduction to how PHP frameworks implement dependency injection using reflection.

Z

Zach Robichaud

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

Comments (0)

Leave a Comment

No comments yet. Be the first to share your thoughts!