首页 > php框架 > Laravel > 正文

Laravel的依赖注入实现原理是什么

WBOY
发布: 2022-02-18 11:06:44
原创
6639人浏览过
在Laravel中,依赖注入的实现原理是利用类方法反射,取得参数类型,然后利用容器构造好实例,再使用回调函数调起;注入对象构造函数不能有参数,否则会报错,依赖注入必须要由Router类调起,否则直接用new方式是无法实现注入的。

Laravel的依赖注入实现原理是什么

本文操作环境:Windows10系统、Laravel6版、Dell G3电脑。

Laravel的依赖注入实现原理是什么

laravel容器包含控制反转和依赖注入,使用起来就是,先把对象bind好,需要时可以直接使用make来取就好。

具体分析参照:http://laravelacademy.org/post/769.html

通常我们的调用如下。

$config = $container->make('config');
$connection = new Connection($this->config);
登录后复制

比较好理解,这样的好处就是不用直接 new 一个实例了,方法传值没啥改变,还可以多处共享此实例。

但这跟依赖注入有什么关系,真正的依赖注入是不需给方法传递任何参数值,只需要指明方法参数类型,代码自动查找关系依赖自动注入。

这个特性在 laravel 的 Controller、Job 等处可以体现,如下:

class TestController extends Controller
{
    public function anyConsole(Request $request, Auth $input)
    {
        //todo
    }
}
登录后复制

我们来看下他是怎么实现自动依赖注入的:

由 index.PHP 调用 Kernel ,经过多层 Kernel 管道调用,再到 Router ,经过多层中间件管道调用。最终定位到

Illuminate/Routing/Route.php 第124行。

public function run(Request $request)
{
    $this->container = $this->container ?: new Container;
    try {
        if (! is_string($this->action['uses'])) {
            return $this->runCallable($request);
        }
        if ($this->customDispatcherIsBound()) {
            return $this->runWithCustomDispatcher($request);
        }
        return $this->runController($request);
    } catch (HttpResponseException $e) {
        return $e->getResponse();
    }
}
登录后复制

判断 $this->action[‘uses’](格式行如:\App\Http\Controller\Datacenter\RealTimeController@anyConsole)是否字符串, $this->customDispatcherIsBound判断是否绑定了用户自定义路由。然后跳转到 $this->runController($request)。

钉钉 AI 助理
钉钉 AI 助理

钉钉AI助理汇集了钉钉AI产品能力,帮助企业迈入智能新时代。

钉钉 AI 助理21
查看详情 钉钉 AI 助理
protected function runController(Request $request)
{
    list($class, $method) = explode('@', $this->action['uses']);
    $parameters = $this->resolveClassMethodDependencies(
        $this->parametersWithoutNulls(), $class, $method
    );
    if (! method_exists($instance = $this->container->make($class), $method)) {
        throw new NotFoundHttpException;
    }
    return call_user_func_array([$instance, $method], $parameters);
}
登录后复制

$this->resolveClassMethodDependencies 这个方法一看名字就知道是我们要找的方法。$this->parametersWithoutNulls()是过滤空字符,$class、$method分别行如:\App\Http\Controller\Datacenter\RealTimeController 与 anyConsole。

protected function resolveClassMethodDependencies(array $parameters, $instance, $method)
{
    if (! method_exists($instance, $method)) {
        return $parameters;
    }
    return $this->resolveMethodDependencies(
        $parameters, new ReflectionMethod($instance, $method)
    );
}
登录后复制

new ReflectionMethod($instance, $method) 是拿到类方法的反射对象,参见文档:http://www.php.net/manual/zh/class.reflectionmethod.php

下面跳转到Illuminate/Routing/RouteDependencyResolverTrait.php 第54行。

public function resolveMethodDependencies(array $parameters, ReflectionFunctionAbstract $reflector)
{
    $originalParameters = $parameters;
    foreach ($reflector->getParameters() as $key => $parameter) {
        $instance = $this->transformDependency(
            $parameter, $parameters, $originalParameters
        );
        if (! is_null($instance)) {
            $this->spliceIntoParameters($parameters, $key, $instance);
        }
    }
    return $parameters;
}
登录后复制

通过反射类方法得到类参数数组,然后遍历传递给 $this->transformDependency 方法。如果实例获取不到则调用 $this->spliceIntoParameters 清楚该参数。

protected function transformDependency(ReflectionParameter $parameter, $parameters, $originalParameters)
{
    $class = $parameter->getClass();
    if ($class && ! $this->alreadyInParameters($class->name, $parameters)) {
        return $this->container->make($class->name);
    }
}
登录后复制

终于看到了容器的影子,没错最终对象还是通过容器的 make 方法取出来的。至此参数就构造好了,然后最终会被 runController 方法的 call_user_func_array 回调。

总结:

依赖注入原理其实就是利用类方法反射,取得参数类型,然后利用容器构造好实例。然后再使用回调函数调起。

注入对象构造函数不能有参数。否则会报错。Missing argument 1

依赖注入故然好,但它必须要由 Router 类调起,否则直接用 new方式是无法实现注入的。所以这就为什么只有 Controller 、Job 类才能用这个特性了。

【相关推荐:laravel视频教程

以上就是Laravel的依赖注入实现原理是什么的详细内容,更多请关注php中文网其它相关文章!

相关标签:
最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号