一个手写的依赖注入的实现代码

    $reflection = new \ReflectionClass(\App\Services\EmailService::class);

        //获取构造方法的对象
        $constructor = $reflection->getConstructor();

        //获取构造方法的参数列表
        $parameters = $constructor->getParameters();

        $newParams = [];

        //遍历参数列表
        foreach ($parameters as $params) {
            // 获取对象
            $dependency = $params->getClass();

            //如果为null
            if (is_null($dependency)) {
                if ($params->isDefaultValueAvailable()) {
                    $newParams[] = $params->getDefaultValue();
                } else {
                    throw new \Exception('Can not resolve class dependency {$parameter->name}');
                }
            //不为null则实例化放入数组
            } else {
                $class = $dependency->name;
                $newParams[] = new $class;
            }
        }

        $service = $reflection->newInstanceArgs($newParams);
        //调用注入类的方法即可    

 

转载于:https://www.cnblogs.com/tudou1223/p/11206819.html

你可能感兴趣的:(一个手写的依赖注入的实现代码)