In Laravel 6, after binding a singleton in the service container, how to reset the parameters of the constructor of the singleton when parsing?
1. Bind a singleton to the service container, the existing implementation is as follows
$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. Now there is a need to reset the parameters of the constructor of the singleton after parsing a singleton. The new implementation is as follows
$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,[]) with the app(ThemeHandler::Class,[‘migrationsLocation’ => ‘E:/wwwroot/object/Modules/ThemeStoreDb/Resources/setting_migrations1’]) The parameters in the construction method are output to the logs respectively, in line with the expectations.
[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"
]