Last active
November 10, 2019 15:26
-
-
Save exileed/c34a9df0d1d4f85e8bf13794e12e3821 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 | |
// PSR-12 | |
// где phpdoc? | |
class Database | |
{ | |
static private $instance = null; | |
private $connect; | |
private $config; | |
private $host; | |
// они тебе не нужны. ты все равно их не используешь. | |
private $login; | |
private $password; | |
private $db; | |
private $sql; | |
private $stmt; | |
private $result; | |
private $types = []; | |
private $params = []; | |
// public static function | |
static public function getInstance(): Database | |
{ | |
// if(self::$instance === null) | |
if (empty(self::$instance)) { | |
self::$instance = new self(); | |
self::$instance->connection(); | |
} | |
return self::$instance; | |
} | |
// почему тут void ? | |
public function query(string $sql, array $types = [], array $params = []): void | |
{ | |
$this->sql = $sql; | |
$this->types = $types; | |
// наркомания. передавай на прямую в функцию check_types | |
$this->params = $params; | |
$numberParams = count($this->params); | |
$numberTypes = count($this->types); | |
try { | |
if ($numberParams != $numberTypes) { | |
// глобальные исключения выкидывать зло. создай свое исключение | |
throw new Exception("Number of parameters and types not match"); | |
} | |
if (!$this->check_types()) { | |
throw new Exception("Types error"); | |
} | |
$this->stmt = $this->connect->prepare($this->sql); | |
// If parameters more then 0 | |
// Запрос "select * from users" может быть без параметров | |
if (!empty($numberParams)) { | |
if (!$this->bind_params()) { | |
// ошибки не понятны совершенно | |
throw new Exception("Bind error"); | |
} | |
} | |
$this->stmt->execute(); | |
$this->result = $this->stmt->get_result(); | |
if ($this->result->num_rows > 0) { | |
$this->result = $this->result->fetch_all(MYSQLI_ASSOC); | |
} | |
$this->stmt->close(); | |
} catch (Exception $e) { | |
// в коде так делать плохо. если это не контроллеры, и т.д | |
printf("Error: %s", $e->getMessage()); | |
if (!empty($this->stmt)) { | |
$this->stmt->close(); | |
} | |
} | |
} | |
public function getResult() | |
{ | |
// бесполезная фигня. лучше сразу возращай результат в query | |
return $this->result; | |
} | |
// bindParams | |
private function bind_params(): bool | |
{ | |
if (empty($this->stmt)) { | |
// уже писал про это | |
printf("Statement not exist"); | |
return false; | |
} | |
$typesString = ''; | |
// тупой хак и не понятно он зачем ? | |
$args = array(&$typesString); | |
$count = count($this->params); | |
for ($i = 0; $i < $count; $i++) { | |
$typesString .= $this->types[$i]; | |
$args[] = &$this->params[$i]; // & - от этого избавляйся. | |
} | |
call_user_func_array(array($this->stmt, 'bind_param'), $args); | |
if ($this->stmt->error) { | |
return false; | |
} | |
return true; | |
} | |
// checkTypes | |
private function check_types(): bool | |
{ | |
foreach ($this->types as $item) { | |
// s, i, d, b в константы бы | |
if ($item !== 's' && $item !== 'i' && $item !== 'd' && $item !== 'b') { | |
return false; | |
} | |
} | |
return true; | |
} | |
private function connection() | |
{ | |
// в отдельный это класс DatabaseConfiguration | |
// зачем тут $this->config ты его не юзаешь | |
$this->config = require __DIR__ . '/../config/db.php'; | |
$this->host = $this->config['mysql']['host']; | |
$this->login = $this->config['mysql']['login']; | |
$this->password = $this->config['mysql']['password']; | |
$this->db = $this->config['mysql']['db']; | |
$this->connect = new mysqli($this->host, $this->login, $this->password, $this->db); | |
if ($this->connect->connect_errno) { | |
// Исключения где | |
printf("Connection database error: %s", $this->connect->connect_errno); | |
} | |
} | |
public function close() | |
{ | |
unset($this->connect); | |
} | |
private function __clone() | |
{ | |
} | |
private function __wakeup() | |
{ | |
} | |
private function __construct() | |
{ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment