「转」Laravel 依赖注入原理(详细注释)

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

本文只是为了转载好文, 原文在此

<?php

namespace Database;

use ReflectionMethod;

class Database
{

    protected $adapter;

    public function __construct()
    {
    }

    public function test(MysqlAdapter $adapter)
    {
        $adapter->test();
    }
}

class MysqlAdapter
{

    public function test()
    {
        echo "i am MysqlAdapter test";
    }
}

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\Database::test with a \Database\MysqlAdapter instance parameter.
        call_user_func_array([
            $instance,
            $method
        ], $parameters);
    }
}

app::run(new Database(), 'test');
本作品采用《CC 协议》,转载必须注明作者和本文链接
日拱一卒
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
未填写
文章
93
粉丝
85
喜欢
153
收藏
121
排名:71
访问:11.4 万
私信
所有博文
社区赞助商