看 Laravel 原始碼瞭解 Container

coding01發表於2018-05-20

自從上文《看 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();
複製程式碼

看 Laravel 原始碼瞭解 Container

如果這時候我們需要將 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();
複製程式碼

結果:

看 Laravel 原始碼瞭解 Container

但這裡有個問題,最後在例項化使用時,還是要「硬編碼」的方式 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();
複製程式碼

看 Laravel 原始碼瞭解 Container

只要有一處繫結了 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

未完待續

相關文章