我目前正在开发一个使用 Hyn 多租户包 5.9 版的 Laravel 项目。我的应用程序需要自定义数据库连接逻辑。具体来说,我需要重写 Connection.php 文件中负责设置数据库连接参数的部分代码。
这是我想要覆盖的代码段:
case static::DIVISION_MODE_SEPARATE_DATABASE:
$clone['username'] = $clone['database'] = $website->uuid;
$clone['password'] = $this->passwordGenerator->generate($website);
是否有推荐的方法来覆盖这些连接参数?
我们可以使用名为 (ConfigurationLoaded) 的 Hyn 事件之一来覆盖这个东西。
创建一个侦听器并像这样覆盖连接凭据。
class TenantDatabaseConfigListener
{
/**
* Handle the event.
*
* @param ConfigurationLoaded $event
* @return void
*/
public function handle(ConfigurationLoaded $event)
{
/** @var Website $website */
$website = $event->website;
$event->configuration['database'] = $website->uuid;
$event->configuration['username'] = 'your username';
$event->configuration['password'] = 'your password';
}
}
然后在 eventServiceProvider 中调用这个监听器如下:
protected $listen = [
'Hyn\Tenancy\Events\Database\ConfigurationLoaded' => [
'App\Listeners\TenantDatabaseConfigListener',
],
]