我不太熟悉拉维尔服务提供商,我有一个问题。
示例:我有三个类SystemProfiler、SurveyProfiler和OfferProfiler,它们实现了ProfilerInterface。还有profilerservice类,它在构造函数中注入profilerinterface。我需要创建不同的profilerservice服务,注入每个profiler。
配置文件服务:

class ProfilerService {

    $this->profiler;

    function __construct(ProfilerInterface $profiler) {
            $this->profiler = profiler;
    }
}

我知道如何在symfony2框架中做到这一点:
system_profiler:
    class: App\MyBundle\Profiles\SystemProfiler

survey_profiler:
    class: App\MyBundle\Profiles\SurveyProfiler

offer_profiler:
    class: App\MyBundle\Profiles\OfferProfiler

system_profile_service:
    class: App\MyBundle\Services\ProfilerService
    arguments:
        - system_profiler

survey_profile_service:
    class: App\MyBundle\Services\ProfilerService
    arguments:
        - survey_profiler

offer_profile_service:
    class: App\MyBundle\Services\ProfilerService
    arguments:
        - offer_profiler

然后用profilerservice实现的别名调用$this->container->get()
但是laravel文档说,“如果类不依赖于任何接口,则不需要将它们绑定到容器中。”profilerservice不依赖于接口。所以我可以把每个剖析器绑定到这样的界面:
   $this->app->bind('App\MyBundle\Contracts\ProfilerInterface','App\MyBundle\Profiles\SystemProfiler');


$this->app->bind('App\MyBundle\Contracts\ProfilerInterface','App\MyBundle\Profiles\SurveyProfiler');


$this->app->bind('App\MyBundle\Contracts\ProfilerInterface','App\MyBundle\Profiles\OfferProfiler');

但是,我应该如何绑定哪些探查器应该被注入到profilerservice以及何时????
我很感激你的帮助和解释

最佳答案

这里是(read the docs):

// ServiceProvider
public function register()
{
    // Simple binding
    $this->app->bind('some_service.one', \App\ImplOne::class);
    $this->app->bind('some_service.two', \App\ImplTwo::class);

    // Aliasing interface - container will inject some_service.one
    // whenever interface is required...
    $this->app->alias('some_service.one', \App\SomeInterface::class);

    // ...except for the Contextual Binding:
    $this->app->when(\App\DependantTwo::class)
              ->needs(\App\SomeInterface::class)
              ->give('some_service.two');
}

使用:
$ php artisan tinker

// Aliases
>>> app('some_service.one')
=> App\ImplOne {#669}
>>> app('some_service.two')
=> App\ImplTwo {#671}

// Aliased interface
>>> app('App\SomeInterface')
=> App\ImplOne {#677}
>>> app('App\DependantOne')->dependency
=> App\ImplOne {#677}

// Contextual
>>> app('App\DependantTwo')->dependency
=> App\ImplOne {#676}

给定此设置:
namespace App;

class ImplOne implements SomeInterface {}

class ImplTwo implements SomeInterface {}

class DependantOne
{
    public function __construct(SomeInterface $dependency)
    {
        $this->dependency = $dependency;
    }
}

class DependantTwo
{
    public function __construct(SomeInterface $dependency)
    {
        $this->dependency = $dependency;
    }
}

08-28 03:02