Skip to content

Instantly share code, notes, and snippets.

@cergey-obr
Last active July 21, 2019 10:37
Show Gist options
  • Save cergey-obr/65af718e04ea0c473b4a560bbba52a3b to your computer and use it in GitHub Desktop.
Save cergey-obr/65af718e04ea0c473b4a560bbba52a3b to your computer and use it in GitHub Desktop.
<?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