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;

        $reflector = new ReflectionMethod($instance, $method);

        $parameters = [
                    1
            ];
        foreach ($reflector->getParameters() as $key => $parameter)
        {

            $class = $parameter->getClass();

            if ($class)
            {
                array_splice($parameters, $key, 0, [
                        new $class->name()
                ]);
            }
        }
        call_user_func_array([
                $instance,
                $method
        ], $parameters);
    }
}

app::run(new Database(), 'test');

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

原文地址:https://www.cnblogs.com/xiashuo-he/p/4890966.html