看 Laravel 源代碼瞭解 Container

自從上文《看 Laravel 源代碼瞭解 ServiceProvider 的加載》,咱們知道 Application (or Container) 充當 Laravel 的容器,基本把全部 Laravel 核心的功能歸入這個容器裏了。php

咱們今天來看看這個 Application / Container 究竟是什麼東西?html

瞭解 Container 以前,咱們須要先簡單說說 Inversion of Control (控制反轉) 的原理。laravel

Inversion of Control

要知道什麼是 Inversion of Control 以前,咱們最好先了解一個原則:編程

依賴倒轉原則 (Dependence Inversion Priciple, DIP)提倡:數組

  • 高層模塊不該該依賴底層模塊。兩個都應該依賴抽象
  • 抽象不該該依賴細節,細節應該依賴抽象
  • 針對接口編程,不要針對實現編程

在編程時,咱們對代碼進行模塊化開發,它們之間避免不了有依賴,如模塊 A 依賴模塊 B,那麼根據 DIP,模塊 A 應該依賴模塊 B 的接口,而不該該依賴模塊 B 的實現。bash

下面咱們舉個例子。閉包

咱們須要一個 Logger 功能,將系統 log 輸出到文件中。咱們能夠能夠這麼寫:app

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

在須要的地方直接調用:ide

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 類的使用,具體參考:php.golaravel.com/class.refle…

代碼往下看:

// 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 pimple.symfony.com

未完待續

相關文章
相關標籤/搜索