Implementing Dependency Injection in PHP Using Reflection

This article explains how to build a simple PHP IoC container with reflection to automatically resolve constructor and method dependencies, demonstrates its use with example classes A, B, and C, and shows how to invoke methods with injected parameters.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Implementing Dependency Injection in PHP Using Reflection

Dependency Injection (DI) is a technique that allows automatic injection of required class dependencies, making code more modular and testable.

The article presents a simple IoC container implemented in PHP using reflection, providing methods getInstance to create class instances and make to invoke methods with injected parameters.

class Ioc {
    public static function getInstance($className) {
        $paramArr = self::getMethodParams($className);
        return (new ReflectionClass($className))->newInstanceArgs($paramArr);
    }

    public static function make($className, $methodName, $params = []) {
        $instance = self::getInstance($className);
        $paramArr = self::getMethodParams($className, $methodName);
        return $instance->$methodName(...array_merge($paramArr, $params));
    }

    protected static function getMethodParams($className, $methodsName = '__construct') {
        $class = new ReflectionClass($className);
        $paramArr = [];
        if ($class->hasMethod($methodsName)) {
            $construct = $class->getMethod($methodsName);
            $params = $construct->getParameters();
            if (count($params) > 0) {
                foreach ($params as $key => $param) {
                    if ($paramClass = $param->getClass()) {
                        $paramClassName = $paramClass->getName();
                        $args = self::getMethodParams($paramClassName);
                        $paramArr[] = (new ReflectionClass($paramClass))->newInstanceArgs($args);
                    }
                }
            }
        }
        return $paramArr;
    }
}

Three example classes (A, B, C) demonstrate constructor injection (B depends on A, A depends on C) and method injection (B's method bb receives C and a manual parameter).

class A {
    protected $cObj;
    public function __construct(C $c) {
        $this->cObj = $c;
    }
    public function aa() {
        echo 'this is A->test';
    }
    public function aac() {
        $this->cObj->cc();
    }
}

class B {
    protected $aObj;
    public function __construct(A $a) {
        $this->aObj = $a;
    }
    public function bb(C $c, $b) {
        $c->cc();
        echo "
";
        echo 'params:' . $b;
    }
    public function bbb() {
        $this->aObj->aac();
    }
}

class C {
    public function cc() {
        echo 'this is C->cc';
    }
}

Using Ioc::getInstance('B') creates a B object with all nested dependencies resolved, and calling Ioc::make('B','bb', ['this is param b']) invokes method bb with automatic injection of C and the supplied parameter.

The examples show that developers no longer need to manually instantiate dependent classes; reflection enables automatic resolution, and the concept can be extended with configuration, caching, and other production‑ready features.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Design Patternsbackend-developmentReflectionPHPdependency-injection
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.