【问题标题】:How does Laravel defer multiple bindings all listed in a single service provider?Laravel 如何延迟多个绑定都列在一个服务提供者中?
【发布时间】:2015-07-08 01:00:15
【问题描述】:

我希望我的所有存储库都列在一个服务提供商中,但我希望它们一次全部加载...

考虑下面的服务提供商:

class RepositoryServiceProvider extends ServiceProvider {

    protected $defer = true;

    public function register()
    {
        $this->app->bind(
            'App\Repositories\Contracts\FooRepository',
            'App\Repositories\SQL\FooSQLRepository');

        $this->app->bind(
            'App\Repositories\Contracts\BarRepository',
            'App\Repositories\SQL\BarSQLRepository');

        // and more to be added later...
    }

    public function provides()
    {

        // Will it defer and load all these at once? Or only the one(s) needed?
        return ['App\Repositories\Contracts\FooRepository',
                'App\Repositories\Contracts\BarRepository'];
    }

}

According to the Laravel docs,我可以将绑定的注册推迟到需要时。但是,当我在单个服务提供者中添加多个绑定时,这是否有效?具体来说,我的意思是,它会延迟然后加载all还是只加载需要的一个

【问题讨论】:

    标签: php laravel laravel-5 service-provider deferred-loading


    【解决方案1】:

    Laravel 将注册所有绑定,即使只需要一个。延迟功能实际上非常简单。首先,创建provides() 中的条目和实际提供者的映射:

    Illuminate\Foundation\ProviderRepository@compileManifest

    if ($instance->isDeferred())
    {
        foreach ($instance->provides() as $service)
        {
            $manifest['deferred'][$service] = $provider;
        }
        $manifest['when'][$provider] = $instance->when();
    }
    

    那么当make()Illuminate\Foundation\Application中被调用时...

    if (isset($this->deferredServices[$abstract]))
    {
        $this->loadDeferredProvider($abstract);
    }
    

    ...并且绑定与延迟提供者之一匹配,它将在此处结束:

    Illuminate\Foundation\Application@registerDeferredProvider

    $this->register($instance = new $provider($this));
    
    if ( ! $this->booted)
    {
        $this->booting(function() use ($instance)
        {
            $this->bootProvider($instance);
        });
    }
    

    如您所知,现在提供程序已照常注册,这意味着调用了 register()boot()。如果您考虑一下,甚至不可能从服务提供者加载一个绑定而不包括其他绑定,因为这一切都是在一种方法中完成的。

    【讨论】:

    • 这个答案让我很伤心,因为现在我需要为每个存储库创建一个服务提供者(因为我不想同时加载所有它们)
    • 我的情况完全一样。如果绑定方法上有一个标志,那就太好了。也许是时候公关了 :)
    猜你喜欢
    • 2018-08-06
    • 2016-04-06
    • 1970-01-01
    • 1970-01-01
    • 2020-03-19
    • 1970-01-01
    • 2016-08-05
    • 2018-04-05
    • 1970-01-01
    相关资源
    最近更新 更多