Last active
July 21, 2019 10:37
-
-
Save cergey-obr/65af718e04ea0c473b4a560bbba52a3b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Service; | |
class DbService | |
{ | |
/** | |
* @var mysqli | |
*/ | |
private static $connection; | |
/** | |
* RuleService constructor. | |
* | |
* @param string $dbUrl | |
* | |
* @throws Exception | |
*/ | |
public function __construct(string $dbUrl) | |
{ | |
$dbParams = parse_url($dbUrl); | |
$connection = new mysqli( | |
$dbParams['host'] ?? '', | |
$dbParams['user'] ?? '', | |
$dbParams['pass'] ?? '', | |
substr($dbParams['path'] ?? '', 1), | |
$dbParams['port'] ?? 3306 | |
); | |
if ($connection->connect_errno) { | |
throw new Exception("Failed connection to database"); | |
} | |
self::$connection = $connection; | |
} | |
/** | |
* @param string $sql | |
* | |
* @return mysqli_result | |
* @throws DbErrorException | |
* @throws Exception | |
*/ | |
public static function execute(string $sql): mysqli_result | |
{ | |
if (!self::$connection) { | |
new DbService($_ENV['DATABASE_URL'] ?? ''); | |
} | |
if (!$result = self::$connection->query($sql)) { | |
throw new DbErrorException('Database error for query: ' . $sql); | |
} | |
return $result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment