Files
kiri-databases/DatabasesProviders.php
T

96 lines
2.2 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;
use Kiri\Exception\ConfigException;
2022-01-14 16:07:57 +08:00
use Kiri\Server\Events\OnTaskerStart;
use Kiri\Server\Events\OnWorkerStart;
2022-01-14 16:11:23 +08:00
use Kiri\Server\Events\OnProcessStart;
2022-01-09 03:49:51 +08:00
/**
* Class DatabasesProviders
* @package Database
*/
class DatabasesProviders extends Providers
{
/**
* @param Application $application
* @throws Exception
*/
public function onImport(Application $application)
{
2022-01-14 16:07:57 +08:00
$this->eventProvider->on(OnWorkerStart::class, [$this, 'createPool']);
2022-01-14 16:11:23 +08:00
$this->eventProvider->on(OnProcessStart::class, [$this, 'createPool']);
2022-01-14 16:07:57 +08:00
$this->eventProvider->on(OnTaskerStart::class, [$this, 'createPool']);
2022-01-09 03:49:51 +08:00
}
/**
* @param $name
* @return Connection
* @throws Exception
*/
public function get($name): Connection
{
return Kiri::app()->get($name);
}
/**
* @throws ConfigException
* @throws Exception
*/
2022-01-14 16:12:20 +08:00
public function createPool(OnTaskerStart|OnWorkerStart|OnProcessStart $onWorkerStart)
2022-01-09 03:49:51 +08:00
{
$databases = Config::get('databases.connections', []);
if (empty($databases)) {
return;
}
$app = Kiri::app();
foreach ($databases as $key => $database) {
$database = $this->_settings($database);
2022-01-09 14:46:34 +08:00
$connection = Kiri::getDi()->create(Connection::class, [$database]);
2022-01-14 16:23:15 +08:00
$connection->fill();
2022-01-09 03:49:51 +08:00
$app->set($key, $connection);
}
}
/**
* @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'],
'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']
];
}
}