在 Laravel 6 中,在服务容器中绑定一个单例后,如何在解析时重新设置单例的构造方法的参数?

1、在服务容器中绑定一个单例,现有的实现如下

$this->app->singleton(ThemeHandler::class, function() {
 return new ThemeHandler(
  base_path('Modules') . '/ThemeStoreDb/Resources/setting_migrations'
 );
});

class ThemeHandler
{
    private $themeSettingMigrator;

    public function __construct(string $defaultMigrationsLocation)
    {
        Log::info(
            '$defaultMigrationsLocation',
            [$defaultMigrationsLocation]
        );
        $this->themeSettingMigrator = new ThemeSettingMigrator($defaultMigrationsLocation);
    }
}

app(ThemeHandler::class)->migrateThemeSettings($this->themeInstallation, $this->themeInstallationTask);

2、现在有需要在解析单例后,可能需要重新设置单例的构造方法的参数。新的实现如下

$this->app->singleton(ThemeHandler::class, function($app, $parameters) {
 return new ThemeHandler(
  $parameters['migrationsLocation'] ?? base_path('Modules') . '/ThemeStoreDb/Resources/setting_migrations'
 );
});

app(ThemeHandler::class, ['migrationsLocation' => 'E:/wwwroot/object/Modules/ThemeStoreDb/Resources/setting_migrations1'])->migrateThemeSettings($this->themeInstallation, $this->themeInstallationTask);

3、app(ThemeHandler::class, []) 与 app(ThemeHandler::class, [‘migrationsLocation’ => ‘E:/wwwroot/object/Modules/ThemeStoreDb/Resources/setting_migrations1’]) 在构造方法中的参数分别输出至日志中,符合预期。


[2023-07-06 15:49:57] local.INFO: $defaultMigrationsLocation [
    "E:\\wwwroot\\object\\Modules/ThemeStoreDb/Resources/setting_migrations"
] 


[2023-07-06 16:16:47] local.INFO: $defaultMigrationsLocation [
    "E:/wwwroot/object/Modules/ThemeStoreDb/Resources/setting_migrations1"
] 
永夜