【问题标题】:Binding the dependency of a Laravel Service Provider inside the provider itself?在提供者本身内部绑定 Laravel 服务提供者的依赖关系?
【发布时间】:2018-12-03 16:00:06
【问题描述】:

我刚刚开始了解服务提供者和 IoC 容器,但有一件事让我感到困惑。我有一个 SpamServiceProvider 需要另外两个类才能运行。然而,其中一个类 InvalidKeywords 有一个数组 $blacklist 参数,需要将其传递给它的构造函数。

如果我在 AppServiceProvider 中注册该类并传入 $blacklist 数组,则一切正常。但是,如果我尝试在 SpamServiceProvider 中绑定类,它不会将 $blacklist 注入 InvalidKeywords 构造函数。

所以我想我的问题是为什么会这样?有没有办法将这样的绑定保持在一个容器中,还是我只需在 AppServiceProvider 中绑定 InvalidKeywords?

这行得通

class SpamServiceProvider extends ServiceProvider
{

/**
 * Indicates if loading of the provider is deferred.
 *
 * @var bool
 */
protected $defer = true;

/**
 * Bootstrap services.
 *
 * @return void
 */
public function boot()
{
    //
}

/**
 * Register services.
 *
 * @return void
 */
public function register()
{

    $this->app->bind(SpamManager::class, function ($app) {
        return new SpamManager(new InvalidKeywords, new RepeatedCharacters);
    });
}

}


class AppServiceProvider extends ServiceProvider
{
/**
 * Register any application services.
 *
 * @return void
 */
public function register()
{
    $this->app->bind(InvalidKeywords::class, function ($app) {
        return new InvalidKeywords(config('spam.blacklist'));
    });
}
}

这不起作用

class SpamServiceProvider extends ServiceProvider
{

/**
 * Indicates if loading of the provider is deferred.
 *
 * @var bool
 */
protected $defer = true;

/**
 * Bootstrap services.
 *
 * @return void
 */
public function boot()
{
    //
}

/**
 * Register services.
 *
 * @return void
 */
public function register()
{

    $this->app->bind(InvalidKeywords::class, function ($app) {
        return new InvalidKeywords(config('spam.blacklist'));
    });

    $this->app->bind(SpamManager::class, function ($app) {
        return new SpamManager(new InvalidKeywords, new RepeatedCharacters);
    });
}
}

【问题讨论】:

    标签: php laravel dependency-injection ioc-container


    【解决方案1】:

    在第二种情况下,您不会从容器中解析 InvalidKeywords 类,而只是创建一个新实例。相反,在创建 SpamManager 时尝试使用 appresolve 助手:

    $this->app->bind(SpamManager::class, function ($app) {
        return new SpamManager(resolve(InvalidKeywords::class), resolve(RepeatedCharacters::class));
    });
    
    // or 
    $this->app->bind(SpamManager::class, function ($app) {
        return new SpamManager(app(InvalidKeywords::class), app(RepeatedCharacters::class));
    });
    

    我也会用InvalidKeywords 创建一个单例:

    $this->app->singleton(InvalidKeywords::class, function ($app) {
        return new InvalidKeywords(config('spam.blacklist'));
    });
    

    【讨论】:

    • 谢谢你!!!我使用了 $app->make() 并且一切都开始工作了:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 2018-07-03
    • 2021-09-23
    • 1970-01-01
    • 2020-03-19
    • 2016-08-05
    相关资源
    最近更新 更多