看 Laravel 源代码了解 Container

本文字数:5360,大概需要 10.72 分钟。

自从上文《看 Laravel 源代码了解 ServiceProvider 的加载》,我们知道 Application (or Container) 充当 Laravel 的容器,基本把所有 Laravel 核心的功能纳入这个容器里了。

我们今天来看看这个 Application / Container 到底是什么东西?

了解 Container 之前,我们需要先简单说说 Inversion of Control (控制反转) 的原理。

Inversion of Control

要知道什么是 Inversion of Control 之前,我们最好先了解一个原则:

依赖倒转原则 (Dependence Inversion Priciple, DIP)提倡:

  • 高层模块不应该依赖底层模块。两个都应该依赖抽象
  • 抽象不应该依赖细节,细节应该依赖抽象
  • 针对接口编程,不要针对实现编程

在编程时,我们对代码进行模块化开发,它们之间避免不了有依赖,如模块 A 依赖模块 B,那么根据 DIP,模块 A 应该依赖模块 B 的接口,而不应该依赖模块 B 的实现。

下面我们举个例子。

我们需要一个 Logger 功能,将系统 log 输出到文件中。我们可以可以这么写:

class LogToFile {
    public function execute($message) {
        info('log the message to a file :'.$message);
    }
}

在需要的地方直接调用:

class UseLogger {
    protected $logger;

    public function __construct(LogToFile $logger) {
        $this->logger = $logger;
    }

    public function show() {
        $user = 'yemeishu';
        $this->logger->execute($user);
    }
}

写个测试用例:

$useLogger = new UseLogger(new LogToFile());

$useLogger->show();

如果这时候我们需要将 log 输出到钉钉上,我们重新写一个 LogToDD 类:

class LogToDD {
    public function execute($message) {
        info('log the message to 钉钉 :'.$message);
    }
}

这时候,我们还需要修改使用端 (UseLogger) 代码,让它引入 LogToDD 类:

class UseLogger {
    protected $logger;

    public function __construct(LogToDD $logger) {
        $this->logger = $logger;
    }

    public function show() {
        $user = 'yemeishu';
        $this->logger->execute($user);
    }
}

其实到这,你就能「嗅出」坏代码来了:

假如我使用端特别多,那就意味着每个地方我都要做引入修改。

根据 DIP 原则,我们应该面向接口开发。让使用端依赖接口,而不是实现。所以我们创建一个接口:

interface Logger {
    public function execute($message);
}

然后让 LogToFileLogToDD 作为 Logger 的实现:

class LogToFile implements Logger {
    public function execute($message) {
        info('log the message to a file :'.$message);
    }
}

class LogToDD implements Logger {
    public function execute($message) {
        info('log the message to 钉钉 :'.$message);
    }
}

这样我们在使用端时,直接引入 Logger 接口,让代码剥离具体实现。

class UseLogger {
    protected $logger;

    public function __construct(Logger $logger) {
        $this->logger = $logger;
    }

    public function show() {
        $user = 'yemeishu';
        $this->logger->execute($user);
    }
}

这样就可以保证,无论是使用文件保存,还是下发到钉钉上,都可以不用去改代码了,只需要再真正调用的时候,随着业务需要自行选择。如测试:

$useLogger1 = new UseLogger(new LogToFile());
$useLogger1->show();

$useLogger2 = new UseLogger(new LogToDD());
$useLogger2->show();

结果:

但这里有个问题,最后在实例化使用时,还是要「硬编码」的方式 new 我们的实现类 (LogToDD or LogToFile)。

那有没有办法更进一步把最后的 new LogToDD() 也控制反转了呢?

绑定的实现

这里我们把实现类绑定在 interface 或者标识 key 上,只要解析这个 interface 或者 key,就可以拿到我们的实现类。

我们来写一个简单的类来达到绑定和解析的功能:

class SimpleContainer {

    // 用于存储所有绑定 key-value
    protected static $container = [];

    public static function bind($name, Callable $resolver) {
        static::$container[$name] = $resolver;
    }

    public static function make($name) {
        if(isset(static::$container[$name])){
            $resolver = static::$container[$name] ;
            return $resolver();
        }
        throw new Exception("Binding does not exist in container");
    }
}

我们可以测试下:

SimpleContainer::bind(Logger::class, function () {
    return new LogToFile();
});

$useLogger3 = new UseLogger(SimpleContainer::make(Logger::class));

$useLogger3->show();

只要有一处绑定了 LoggerLogToFile 的关系,就可以在任何需要调用的地方直接解析引用了。

也就意味着,通过这种方法,在所有编码的地方都是引入「interface」,而不是实现类。彻底实现 DPI 原则。

当我们把所有这种绑定聚集在一起,就构成了我们今天的主题内容:「Container」—— illuminate / container。

Laravel Container

在研究 Laravel Container 之前,我们根据上面的例子,使用 Container,看怎么方便实现。

$container = new Container();
$container->bind(Logger::class, LogToFile::class);

$useLogger4 = new UseLogger($container->make(Logger::class));
$useLogger4->show();

达到一样的效果

[2018-05-19 15:36:30] testing.INFO: log the message to a file :yemeishu

注:在 Laravel 开发时,我们会把这个绑定写在 APPServiceProvider 的 boot 或者 register 中,或者其他的 ServiceProvider 上也行。

结合上一篇文章《看 Laravel 源代码了解 ServiceProvider 的加载》和以上的原理的讲解。我们对 Container 的使用,已经不陌生了。

接下来就可以看看 Container 的源代码了。

Container 源码解析

从上文可以知道,Container 的作用主要有两个,一个是绑定,另个一个是解析。

绑定

我们看看主要有哪些绑定类型:

  1. 绑定一个单例
  2. 绑定实例
  3. 绑定接口到实现
  4. 绑定初始数据
  5. 情境绑定
  6. tag 标记绑定

下面我们根据这些类型进行分析:

1. 绑定一个单例

public function singleton($abstract, $concrete = null)
    {
        $this->bind($abstract, $concrete, true);
    }

主要利用参数 $share = true 来标记此时绑定为一个单例。

2. 绑定实例

public function instance($abstract, $instance)
{
    $this->removeAbstractAlias($abstract);

    $isBound = $this->bound($abstract);

    unset($this->aliases[$abstract]);

    // We'll check to determine if this type has been bound before, and if it has
    // we will fire the rebound callbacks registered with the container and it
    // can be updated with consuming classes that have gotten resolved here.
    $this->instances[$abstract] = $instance;

    if ($isBound) {
        $this->rebound($abstract);
    }

    return $instance;
}

绑定实例,主要是将 [$abstract, $instance]存储进数组 $instances 中。

3. tag 标记绑定

/**
 * Assign a set of tags to a given binding.
 *
 * @param  array|string  $abstracts
 * @param  array|mixed   ...$tags
 * @return void
 */
public function tag($abstracts, $tags)
{
    $tags = is_array($tags) ? $tags : array_slice(func_get_args(), 1);

    foreach ($tags as $tag) {
        if (! isset($this->tags[$tag])) {
            $this->tags[$tag] = [];
        }

        foreach ((array) $abstracts as $abstract) {
            $this->tags[$tag][] = $abstract;
        }
    }
}

这个挺好理解,主要是将 $abstracts 数组放在同一组标签下,最后可以通过 tag,解析这一组 $abstracts

4. 绑定

public function bind($abstract, $concrete = null, $shared = false)
{
    // If no concrete type was given, we will simply set the concrete type to the
    // abstract type. After that, the concrete type to be registered as shared
    // without being forced to state their classes in both of the parameters.
    $this->dropStaleInstances($abstract);

    // 如果传入的实现为空,则绑定 $concrete 自己
    if (is_null($concrete)) {
        $concrete = $abstract;
    }

    // If the factory is not a Closure, it means it is just a class name which is
    // bound into this container to the abstract type and we will just wrap it
    // up inside its own Closure to give us more convenience when extending.
    // 目的是将 $concrete 转成闭包函数
    if (! $concrete instanceof Closure) {
        $concrete = $this->getClosure($abstract, $concrete);
    }

    // 存储到 $bindings 数组中,如果 $shared = true, 则表示绑定单例
    $this->bindings[$abstract] = compact('concrete', 'shared');

    // If the abstract type was already resolved in this container we'll fire the
    // rebound listener so that any objects which have already gotten resolved
    // can have their copy of the object updated via the listener callbacks.
    if ($this->resolved($abstract)) {
        $this->rebound($abstract);
    }
}

解析

/**
 * Resolve the given type from the container.
 *
 * @param  string  $abstract
 * @param  array  $parameters
 * @return mixed
 */
public function make($abstract, array $parameters = [])
{
    return $this->resolve($abstract, $parameters);
}

/**
 * Resolve the given type from the container.
 *
 * @param  string  $abstract
 * @param  array  $parameters
 * @return mixed
 */
protected function resolve($abstract, $parameters = [])
{
    $abstract = $this->getAlias($abstract);

    $needsContextualBuild = ! empty($parameters) || ! is_null(
        $this->getContextualConcrete($abstract)
    );

    // If an instance of the type is currently being managed as a singleton we'll
    // just return an existing instance instead of instantiating new instances
    // so the developer can keep using the same objects instance every time.
    if (isset($this->instances[$abstract]) && ! $needsContextualBuild) {
        return $this->instances[$abstract];
    }

    $this->with[] = $parameters;

    $concrete = $this->getConcrete($abstract);

    // We're ready to instantiate an instance of the concrete type registered for
    // the binding. This will instantiate the types, as well as resolve any of
    // its "nested" dependencies recursively until all have gotten resolved.
    if ($this->isBuildable($concrete, $abstract)) {
        $object = $this->build($concrete);
    } else {
        $object = $this->make($concrete);
    }

    // If we defined any extenders for this type, we'll need to spin through them
    // and apply them to the object being built. This allows for the extension
    // of services, such as changing configuration or decorating the object.
    foreach ($this->getExtenders($abstract) as $extender) {
        $object = $extender($object, $this);
    }

    // If the requested type is registered as a singleton we'll want to cache off
    // the instances in "memory" so we can return it later without creating an
    // entirely new instance of an object on each subsequent request for it.
    if ($this->isShared($abstract) && ! $needsContextualBuild) {
        $this->instances[$abstract] = $object;
    }

    $this->fireResolvingCallbacks($abstract, $object);

    // Before returning, we will also set the resolved flag to "true" and pop off
    // the parameter overrides for this build. After those two things are done
    // we will be ready to return back the fully constructed class instance.
    $this->resolved[$abstract] = true;

    array_pop($this->with);

    return $object;
}

我们一步步来分析该「解析」函数:

$needsContextualBuild = ! empty($parameters) || ! is_null(
    $this->getContextualConcrete($abstract)
);

该方法主要是区分,解析的对象是否有参数,如果有参数,还需要对参数做进一步的分析,因为传入的参数,也可能是依赖注入的,所以还需要对传入的参数进行解析;这个后面再分析。

// If an instance of the type is currently being managed as a singleton we'll
// just return an existing instance instead of instantiating new instances
// so the developer can keep using the same objects instance every time.
if (isset($this->instances[$abstract]) && ! $needsContextualBuild) {
    return $this->instances[$abstract];
}

如果是绑定的单例,并且不需要上面的参数依赖。我们就可以直接返回 $this->instances[$abstract]

$concrete = $this->getConcrete($abstract);

...

/**
 * Get the concrete type for a given abstract.
 *
 * @param  string  $abstract
 * @return mixed   $concrete
 */
protected function getConcrete($abstract)
{
    if (! is_null($concrete = $this->getContextualConcrete($abstract))) {
        return $concrete;
    }

    // If we don't have a registered resolver or concrete for the type, we'll just
    // assume each type is a concrete name and will attempt to resolve it as is
    // since the container should be able to resolve concretes automatically.
    if (isset($this->bindings[$abstract])) {
        return $this->bindings[$abstract]['concrete'];
    }

    return $abstract;
}

这一步主要是先从绑定的上下文找,是不是可以找到绑定类;如果没有,则再从 $bindings[] 中找关联的实现类;最后还没有找到的话,就直接返回 $abstract 本身。

// We're ready to instantiate an instance of the concrete type registered for
// the binding. This will instantiate the types, as well as resolve any of
// its "nested" dependencies recursively until all have gotten resolved.
if ($this->isBuildable($concrete, $abstract)) {
    $object = $this->build($concrete);
} else {
    $object = $this->make($concrete);
}

...

/**
 * Determine if the given concrete is buildable.
 *
 * @param  mixed   $concrete
 * @param  string  $abstract
 * @return bool
 */
protected function isBuildable($concrete, $abstract)
{
    return $concrete === $abstract || $concrete instanceof Closure;
}

这个比较好理解,如果之前找到的 $concrete 返回的是 $abstract 值,或者 $concrete 是个闭包,则执行 $this->build($concrete),否则,表示存在嵌套依赖的情况,则采用递归的方法执行 $this->make($concrete),直到所有的都解析完为止。

$this->build($concrete)

/**
 * Instantiate a concrete instance of the given type.
 *
 * @param  string  $concrete
 * @return mixed
 *
 * @throws \Illuminate\Contracts\Container\BindingResolutionException
 */
public function build($concrete)
{
    // If the concrete type is actually a Closure, we will just execute it and
    // hand back the results of the functions, which allows functions to be
    // used as resolvers for more fine-tuned resolution of these objects.
    // 如果传入的是闭包,则直接执行闭包函数,返回结果
    if ($concrete instanceof Closure) {
        return $concrete($this, $this->getLastParameterOverride());
    }

    // 利用反射机制,解析该类。
    $reflector = new ReflectionClass($concrete);

    // If the type is not instantiable, the developer is attempting to resolve
    // an abstract type such as an Interface of Abstract Class and there is
    // no binding registered for the abstractions so we need to bail out.
    if (! $reflector->isInstantiable()) {
        return $this->notInstantiable($concrete);
    }

    $this->buildStack[] = $concrete;

    // 获取构造函数
    $constructor = $reflector->getConstructor();

    // If there are no constructors, that means there are no dependencies then
    // we can just resolve the instances of the objects right away, without
    // resolving any other types or dependencies out of these containers.
    // 如果没有构造函数,则表明没有传入参数,也就意味着不需要做对应的上下文依赖解析。
    if (is_null($constructor)) {
        // 将 build 过程的内容 pop,然后直接构造对象输出。
        array_pop($this->buildStack);

        return new $concrete;
    }

    // 获取构造函数的参数
    $dependencies = $constructor->getParameters();

    // Once we have all the constructor's parameters we can create each of the
    // dependency instances and then use the reflection instances to make a
    // new instance of this class, injecting the created dependencies in.
    // 解析出所有上下文依赖对象,带入函数,构造对象输出
    $instances = $this->resolveDependencies(
        $dependencies
    );

    array_pop($this->buildStack);

    return $reflector->newInstanceArgs($instances);
}

此方法分成两个分支:如果 $concrete instanceof Closure,则直接调用闭包函数,返回结果:$concrete();另一种分支就是,传入的就是一个 $concrete === $abstract === 类名,通过反射方法,解析并 new 该类。

具体解释看上面的注释。 ReflectionClass 类的使用,具体参考:https://php.golaravel.com/class.reflectionclass.html

代码往下看:

// If we defined any extenders for this type, we'll need to spin through them
// and apply them to the object being built. This allows for the extension
// of services, such as changing configuration or decorating the object.
foreach ($this->getExtenders($abstract) as $extender) {
    $object = $extender($object, $this);
}

// If the requested type is registered as a singleton we'll want to cache off
// the instances in "memory" so we can return it later without creating an
// entirely new instance of an object on each subsequent request for it.
if ($this->isShared($abstract) && ! $needsContextualBuild) {
    $this->instances[$abstract] = $object;
}

$this->fireResolvingCallbacks($abstract, $object);

// Before returning, we will also set the resolved flag to "true" and pop off
// the parameter overrides for this build. After those two things are done
// we will be ready to return back the fully constructed class instance.
$this->resolved[$abstract] = true;

array_pop($this->with);

return $object;

这些就比较好理解了。主要判断是否存在扩展,则相应扩展功能;如果是绑定单例,则将解析的结果存到 $this->instances 数组中;最后做一些解析的「善后工作」。

最后我们再看看 tag 标签的解析:

/**
 * Resolve all of the bindings for a given tag.
 *
 * @param  string  $tag
 * @return array
 */
public function tagged($tag)
{
    $results = [];

    if (isset($this->tags[$tag])) {
        foreach ($this->tags[$tag] as $abstract) {
            $results[] = $this->make($abstract);
        }
    }

    return $results;
}

现在看这个就更好理解了,如果传入的 tag 标签值存在 tags 数组中,则遍历所有 $abstract, 一一解析,将结果保存数组输出。

总结

虽然 Container 核心的内容我们了解了,但还有很多细节值得我们接着研究,如:$alias 相关的,事件相关的,扩展相关的。

最后收尾,推荐大家看看这个 Container:silexphp/Pimple

A small PHP 5.3 dependency injection container https://pimple.symfony.com

未完待续

原文发布于微信公众号 - coding01(coding01)

原文发表时间:2018-05-20

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏Java 源码分析

synchronized 原理分析

synchronized 原理分析 1. 在阅读源码时做了大量的注释,并且做了一些测试分析源码内的执行流程,由于博客篇幅有限,并且代码阅读起来没有 IDE 方...

26830
来自专栏互联网开发者交流社区

jsp 内置对象(五)

13350
来自专栏Java学习网

Java中使用Hibernate系列之单向Set-based的关联学习(第四节)

接着学习,后续5个章节中我们将学习Hibernate关联映射的相关知识,前面我们已经映射了一个持久化实体类到表上,现在在这个基础上增加一些类之间的关联,首先我们...

24190
来自专栏MasiMaro 的技术博文

VC++ 崩溃处理以及打印调用堆栈

一般当程序发生异常时,用户代码停止执行,并将CPU的控制权转交给操作系统,操作系统接到控制权后,将当前线程的环境保存到结构体CONTEXT中,然后查找针对此异常...

45140
来自专栏编程

Java并发编程实战

在我们的实际应用当中可能经常会遇到这样一个场景:多个线程读或者、写相同的数据,访问相同的文件等等。对于这种情况如果我们不加以控制,是非常容易导致错误的。在jav...

27750
来自专栏落影的专栏

静态库与动态库的思考

前言 在上文《编译与链接过程的思考》评论中暴走大牙提到了静态库和动态库依赖的问题,还在群里提了几个测试样例和测试工程。 大致介绍下测试工程和如何进行测试: ...

39760
来自专栏Jed的技术阶梯

Apache Avro 入门

Apache Avro(以下简称 Avro)是一种与编程语言无关的序列化格式。Doug Cutting 创建了这个项目,目的是提供一种共享数据文件的方式。

61010
来自专栏开发与安全

linux网络编程之socket(六):利用recv和readn函数实现readline函数

在前面的文章中,我们为了避免粘包问题,实现了一个readn函数读取固定字节的数据。如果应用层协议的各字段长度固定,用readn来读是非常方便的。例如设计一种客户...

27500
来自专栏JavaEdge

JMM1、基础与概念2、重排序6、锁7、java concurrent包的通用化的实现模式7、final8、双重检查和延迟优化

32190
来自专栏微信公众号:Java团长

Java网络爬虫基础知识

Java 网络爬虫具有很好的扩展性可伸缩性,其是目前搜索引擎开发的重要组成部分。例如,著名的网络爬虫工具 Nutch 便是采用 Java 开发,该工具以 Apa...

17920

扫码关注云+社区

领取腾讯云代金券