浅谈 Laravel Container 及其项目实践

520 阅读3分钟
原文链接: laravel-china.org

前言

目前后台是使用Laravel框架写的,最近在把其中的订单处理部分抽出来,准备写个单独的Library。特地好好的研究了一下设计模式,Laravel学院上面有一个专题,便是谈设计模式的,甚好!

为了降低耦合性,在我的项目中使用了Laravel Container以支持IoC(控制反转)。但是就如何在Laravel之外使用illuminate/container这方面资料寥寥无几,所以这篇文章记录一下自己的学习心得。

背景知识

  • php/composer
  • IoC

安装

直接使用composer:

composer require illuminate/container

Laravel之外使用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则主要是用于将实例与一个上下文情景进行绑定。这两部分都是比较高级的内容,这里不作展开了。