淺談 Laravel Container 及其專案實踐

william發表於2017-03-13

目前後臺是使用Laravel框架寫的,最近在把其中的訂單處理部分抽出來,準備寫個單獨的Library。特地好好的研究了一下設計模式,Laravel學院上面有一個專題,便是談設計模式的,甚好!

為了降低耦合性,在我的專案中使用了Laravel Container以支援IoC(控制反轉)。但是就如何在Laravel之外使用illuminate/container這方面資料寥寥無幾,所以這篇文章記錄一下自己的學習心得。

  • php/composer
  • IoC

直接使用composer:

composer require illuminate/container

還是以我的Order專案為例,用其中的部分作為講解。先看一下部分架構圖。
架構圖
訂單生成的主要流程:Cashier通過OrderFactory來生成訂單,OrderFactory內部存在一條Pipeline,資料以流的形式在Pipeline中流經各個PipeWorker,通過不同的加工階段最終生成訂單。

  • Container

首先需要在自己專案中定義一個容器物件,來“容納”所有的例項或者方法等。這裡我將Cashier類作為統一的對外處理物件,它繼承自Illuminate\Container\Container

一般配置資訊會作為容器的建構函式的引數。在Laravel中,由於配置內容較多,這一形式表現為__construct函式中的$basePath引數。通過約定的目錄結構結合$appPath動態讀取配置資訊。本專案則選擇直接給予一個Config類的形式,注入配置資訊。Config類實質是一個鍵值對的陣列。

class Cashier extends Container implements \WilliamWei\FancyOrder\Contracts\Cashier
{
    protected $providers = [
        OrderServiceProvider::class,
        PipelineServiceProvider::class,
    ];

    public function __construct($config)
    {
        $this['config'] = function () use ($config) {
            return new Config($config);
        };

        //register the provider
        foreach ($this->providers as $provider)
        {
            $provider = new $provider();
            $provider->register($this);
        }

    }
}

Illuminate\Container\Container已經實現了ArrayAccess介面,可以直接以陣列方式訪問容器中的物件。構造時,首先為config物件定義例項化的閉包函式。然後依次將各個模組對應的ServiceProvider進行註冊。

  • ServiceProvider

將專案劃分為更小的子模組有助於控制規模,可以大大提高可維護性以及可測試性。每個子模組都有一個ServiceProvider,用於暴露本模組可提供的服務物件。自定義的ServiceProvider可以繼承Illuminate\Support\ServiceProvider,這裡我是選擇自己實現的ServiceProvider
介面:

interface ServiceProvider
{
    public function register(Container $app);
}

以PipelineServiceProvider為例:

class PipelineServiceProvider implements ServiceProvider
{
    public function register(Container $app)
    {
        $workers = [];

        foreach ($app['config']['pipeline_workers'] as $name => $worker)
        {
            $app->bind($name,function($app) use ($worker) {
                return new $worker();
            });

            array_push($workers,$app[$name]);
        }

        $app->bind('pipeline',function($app) use ($workers) {
            return new Pipeline($workers);
        });
    }
}

PipelineServiceProviderregister方法中,將特定函式與例項的名字進行繫結,當通過該名字訪問例項時,若物件不存在,則容器會呼叫被繫結的函式來例項化一個物件,並將其置於容器,以供後續呼叫使用。對於Pipeline,他並不需要關心是哪些Pipeworker在工作,只需要知道他們存在,並且可以正常工作就好,從而以這種形式達到解耦目的。

當然有可能有時候需要訪問容器內其他物件,則可以將容器本身作為建構函式的引數傳入,如:

$app->bind('pipeline',function($app) use ($workers) {
    return new Pipeline($app,$workers);
});

那麼在Pipeline內部就可以通過
$this->app['XXX']的形式訪問XXX物件,同時也無需關心XXX是如何構造的。

這裡的程式碼分析部分只關注主體部分,不會面面具到的分析到每個函式。

可以看到整個包一共就3個PHP檔案,最核心的是Container.php,它定義了容器類,並實現了其中絕大多數功能。當我們bind一個例項到通過[]下標訪問時發生了什麼?

    /**
     * Register a binding with the container.
     *
     * @param  string|array  $abstract
     * @param  \Closure|string|null  $concrete
     * @param  bool  $shared
     * @return void
     */
    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);

        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.
        if (! $concrete instanceof Closure) {
            $concrete = $this->getClosure($abstract, $concrete);
        }

        $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);
        }
    }

這是bind函式,當我們執行一個繫結操作時,容器首先會把該名字之前繫結的例項與別名清除掉,即$this->dropStaleInstances($abstract);如果該名字對應例項是已經解析過的,則會觸發rebound,執行對應回撥。對於第一次繫結則不會出現這種情況。到此bind就結束了。

當通過下標方式獲取例項時

    public function offsetGet($key)
    {
        return $this->make($key);
    }

可以看到呼叫了make方法。

    /**
     * Resolve the given type from the container.
     *
     * @param  string  $abstract
     * @return mixed
     */
    public function make($abstract)
    {
        $needsContextualBuild = ! is_null(
            $this->getContextualConcrete($abstract = $this->getAlias($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];
        }

        $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);

        $this->resolved[$abstract] = true;

        return $object;
    }

略有些複雜,大致流程是先檢查例項陣列中該例項是否存在,存在的話則返回。對於不存在的情況,由於我們是實用閉包的方式進行bind,所以會呼叫該閉包,即$object = $this->build($concrete);得到$object。後面會通知該例項對應類的子類,告知他們該例項已被建立。註冊該例項到例項陣列,(如果存在解析完成回撥函式則會去執行),返回例項。

這個便是容器內部的一個流程。

BoundMethod.php主要以靜態的形式實現了直接呼叫某個類的某一方法的目標。

ContextualBindingBuilder.php則主要是用於將例項與一個上下文情景進行繫結。這兩部分都是比較高階的內容,這裡不作展開了。

歡迎關注個人部落格 :)

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章