Money and Remote services
This commit is contained in:
58
app/Alias/RemoteConnection.php
Normal file
58
app/Alias/RemoteConnection.php
Normal file
@ -0,0 +1,58 @@
|
||||
<?php
|
||||
namespace App\Alias;
|
||||
|
||||
use PDO;
|
||||
use PDOException;
|
||||
|
||||
class RemoteConnection
|
||||
{
|
||||
public function __construct(protected int $retries = 5)
|
||||
{
|
||||
$this->host = $_ENV['REMOTE_HOST'];
|
||||
$this->database = $_ENV['REMOTE_DATABASE'];
|
||||
$this->username = $_ENV['REMOTE_USER'];
|
||||
$this->password = $_ENV['REMOTE_PASSWORD'];
|
||||
if (isset($_ENV['REMOTE_PORT'])) {
|
||||
$this->port = $_ENV['REMOTE_PORT'];
|
||||
}
|
||||
}
|
||||
|
||||
protected string $host;
|
||||
protected string $database;
|
||||
protected int $port;
|
||||
protected string $username;
|
||||
protected string $password;
|
||||
|
||||
protected PDO $connection;
|
||||
public function connect(): PDO
|
||||
{
|
||||
if (!isset($this->connection)) {
|
||||
$r = 0;
|
||||
$exception = null;
|
||||
while ($r < $this->retries) {
|
||||
try {
|
||||
$dsn = $this->getDsn();
|
||||
$this->connection = new PDO($dsn, $this->username, $this->password);
|
||||
} catch (PDOException $e) {
|
||||
if ($exception !== null) {
|
||||
$e = new PDOException($e->getMessage(), $e->getCode(), $exception);
|
||||
}
|
||||
$exception = $e;
|
||||
usleep(500);
|
||||
}
|
||||
$r ++;
|
||||
}
|
||||
throw $exception;
|
||||
}
|
||||
return $this->connection;
|
||||
}
|
||||
|
||||
protected function getDsn(): string
|
||||
{
|
||||
$dsn = "mysql:host={$this->host};dbname={$this->database}";
|
||||
if (isset($this->port)) {
|
||||
$dsn .= ";port={$this->port}";
|
||||
}
|
||||
return $dsn;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user