Laravel: dynamic configuration for Pusher

最后都变了- 提交于 2021-02-11 08:44:07

问题


I am trying to make the configuration for Pusher in my Laravel app (SaaS) dynamic. Basically I want to store different Pusher configs for different accounts. And call the corresponding config based on the user.

I have tries to change the config in runtime using config()->set('services.pusher.xxx', 'yyyy'), but this doesn't work at any level of the framework, event in a custom ServiceProvider.

I found Laravel's BroadcastManager and tried to override the createPusherDriver() so that I could create a custom instance of PusherBroadcaster with the user's config, but I am not sure how to do that or where to put it!

What is the best-practice/standard way to do that?


回答1:


I've been using a setup like this in one of my own projects, to set a custom mail config:

NOTE: Your mileage may vary due to the order in which service providers are loaded in your app.

Create a serviceprovider like app\Providers\ConfigProvider.php

public function boot()
{
    $this->app->booted(function () {
        $shouldSetCustomConfig = true;
        // Set config values from database.
        if($shouldSetCustomConfig) {
            config([
                'mail.host' => Config::get('mail.host'),
                'mail.port' => Config::get('mail.port'),
            ]);
        }
    });
}
  • The $this->app->booted() is a simple callback that gets called after the application has been booted. This might not always work correctly because I've seen various packages that use this callback too to do various stuff. When this is the case, the order of registration matters. Note that it is not required to use this callback. One might simply call the config(['key' => 'newval']) directly and it could work as intended.
  • The service provider above should be loaded BEFORE the provider you are setting configuration for. In the example above it would be the Illuminate\Mail\MailServiceProvider::class. This should make sure the correct config is loaded.


来源:https://stackoverflow.com/questions/59612302/laravel-dynamic-configuration-for-pusher

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!