浅谈Laravel Container及其项目实践

前言

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

欢迎关注个人博客 :)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 222,378评论 6 516
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,970评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 168,983评论 0 362
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,938评论 1 299
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,955评论 6 398
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,549评论 1 312
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 41,063评论 3 422
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,991评论 0 277
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,522评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,604评论 3 342
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,742评论 1 353
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,413评论 5 351
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 42,094评论 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,572评论 0 25
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,671评论 1 274
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 49,159评论 3 378
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,747评论 2 361

推荐阅读更多精彩内容

  • 先说几句废话,调和气氛。事情的起由来自客户需求频繁变更,伟大的师傅决定横刀立马的改革使用新的框架(created ...
    wsdadan阅读 3,054评论 0 12
  • 这本书是以期末考试来临,从小子书包里截留下来的。其实他已经读完一遍,而我花了三个晚上,读读停停,不能流畅的...
    明续阅读 833评论 2 0
  • 学了第五单元,我懂得了生命与水的关系,没有水就没有我们人类,没有水,人们就会死亡 我学了《古诗二首》过分水岭,饮湖...
    王明亮_fcc0阅读 167评论 2 2
  • 01 前阵子我在朋友圈发了一条状态,收到了接二连三的回复,其中一条是“你搬家了?是结婚了吗?”我回复她说没有结婚。...
    star心中无别人阅读 581评论 0 0