Laravel 依赖注入原理

众所周知 Laravel 的文档对于依赖注入只写了如何使用,相信大多数人对于他的实现原理并不太清楚。虽然使用过程中并不需要关心她的原理,但是了解原理让你使用起来更自信。这个帖子就通过一个小 demo 来简述实现原理,demo 如下,该 demo 可直接运行:

代码已被折叠,点此展开

原理主要运用了 PHP 反射 api 的 ReflectionMethod 类,在 PHP 运行状态中,扩展分析 PHP 程序。具体使用可查看手册。

本帖已被设为精华帖!
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
讨论数量: 21
//array_splice($parameters, $key, 0, [
//                        new $class->name()
//                ]);
$parameters = [new $class->name()];

一个小小的问题:对 array_splice 这一句有困惑。

8年前 评论

简单注释一下备忘

class app
{

    public static function run($instance, $method)
    {
        if (!method_exists($instance, $method)) {
            return null;
        }

        //ReflectionMethod::__construct — Constructs a ReflectionMethod
        $reflector = new ReflectionMethod($instance, $method);
        //The ReflectionMethod class reports information about a method. See here:
        // http://php.net/manual/en/class.reflectionmethod.php

        //preset an array which can be empty or not.
        $parameters = [];

        //ReflectionFunctionAbstract::getParameters — Gets parameters
        //Get the parameters as an array of ReflectionParameter.
        //The ReflectionParameter class retrieves information about function's or method's parameters.
        //See here: http://php.net/manual/en/class.reflectionparameter.php
        foreach ($reflector->getParameters() as $key => $parameter) {
            //ReflectionParameter::getClass — Get the type hinted class.
            //http://php.net/manual/en/reflectionparameter.getclass.php
            $class = $parameter->getClass();

            if ($class) {
                //array_splice — Remove a portion of the array and replace it with something else.
                //If length is specified and is zero, no elements will be removed(That is insert!)
                array_splice($parameters, $key, 0, [
                    new $class->name()
                ]);
            }
        }
        //call_user_func_array — Call a callback with an array of parameters
        //So the code below is to invoke \Database\MysqlAdapter::test with a \Database\MysqlAdapter instance.
        call_user_func_array([
            $instance,
            $method
        ], $parameters);
    }
}
6年前 评论

依赖注入怎么能少得了更进一步的容器呢(/ 摊手)

6年前 评论