Files
kiri-databases/DatabasesProviders.php
T

77 lines
1.7 KiB
PHP
Raw Normal View History

2022-01-09 03:49:51 +08:00
<?php
declare(strict_types=1);
namespace Database;
use Exception;
2022-01-14 16:07:57 +08:00
use Kiri;
2022-01-09 03:49:51 +08:00
use Kiri\Abstracts\Config;
use Kiri\Abstracts\Providers;
use Kiri\Application;
2022-02-18 15:11:44 +08:00
use Kiri\Exception\ConfigException;
2022-01-09 03:49:51 +08:00
/**
* Class DatabasesProviders
* @package Database
*/
class DatabasesProviders extends Providers
{
/**
* @param Application $application
2022-02-17 18:31:33 +08:00
* @return void
2022-02-18 15:28:29 +08:00
* @throws ConfigException
2022-01-09 03:49:51 +08:00
*/
public function onImport(Application $application)
{
2022-02-18 15:28:29 +08:00
$databases = Config::get('databases.connections', []);
if (empty($databases)) {
return;
}
$app = Kiri::app();
foreach ($databases as $key => $database) {
$app->set($key, $this->_settings($database));
}
2022-01-09 03:49:51 +08:00
}
/**
* @param $name
* @return Connection
* @throws Exception
*/
public function get($name): Connection
{
return Kiri::app()->get($name);
}
/**
* @param $database
* @return array
*/
private function _settings($database): array
{
$clientPool = $database['pool'] ?? ['min' => 1, 'max' => 5, 'tick' => 60];
return [
'id' => $database['id'],
'cds' => $database['cds'],
2022-02-18 15:28:29 +08:00
'class' => Connection::class,
2022-01-09 03:49:51 +08:00
'username' => $database['username'],
'password' => $database['password'],
'tablePrefix' => $database['tablePrefix'],
'database' => $database['database'],
'connect_timeout' => $database['connect_timeout'] ?? 30,
'read_timeout' => $database['read_timeout'] ?? 10,
'pool' => $clientPool,
'attributes' => $database['attributes'] ?? [],
'charset' => $database['charset'] ?? 'utf8mb4',
'slaveConfig' => $database['slaveConfig']
];
}
}