Created
February 5, 2019 12:42
-
-
Save gustavonovaes/694214f512f20e3abea1967ffdb92ea3 to your computer and use it in GitHub Desktop.
Helper para PDO
This file contains hidden or 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 | |
class DB | |
{ | |
/** | |
* @var \PDO | |
*/ | |
private $pdo; | |
public function __construct(string $dsn, string $username, string $passwd, array $options = []) | |
{ | |
$this->pdo = new \PDO($dsn, $username, $passwd, $options); | |
} | |
public function exec(string $sql, array $params = []) : int | |
{ | |
return $this->prepare($sql, $params) | |
->rowCount(); | |
} | |
private function prepare(string $sql, array $params) : \PDOStatement | |
{ | |
$stmt = $this->pdo->prepare($sql); | |
if (!$stmt) { | |
throw new \PDOException('Falha ao preparar query'); | |
} | |
foreach ($params as $key => $value) { | |
$stmt->bindValue($key, $value); | |
} | |
if (!$stmt->execute()) { | |
throw new \PDOException('Falha ao executar query'); | |
} | |
return $stmt; | |
} | |
public function queryAll(string $sql, array $params = []) : array | |
{ | |
return $this->prepare($sql, $params) | |
->fetchAll(\PDO::FETCH_ASSOC); | |
} | |
public function queryOne(string $sql, array $params = []) | |
{ | |
$rows = $this->prepare($sql, $params) | |
->fetchAll(\PDO::FETCH_NUM); | |
if (!count($rows)) { | |
return false; | |
} | |
return current(current($rows)); | |
} | |
public function queryRow(string $sql, array $params = []) : array | |
{ | |
$rows = $this->prepare($sql, $params) | |
->fetchAll(\PDO::FETCH_ASSOC); | |
return current($rows); | |
} | |
public function queryColumn(string $sql, array $params = [], int $column = 0) : array | |
{ | |
$rows = $this->prepare($sql, $params) | |
->fetchAll(\PDO::FETCH_NUM); | |
return array_column($rows, $column); | |
} | |
public function transaction($closure) : bool | |
{ | |
$this->pdo->beginTransaction(); | |
try { | |
$closure($this); | |
return $this->pdo->commit(); | |
} catch (\Exception $e) { | |
$this->pdo->rollBack(); | |
throw $e; | |
} | |
} | |
public function beginTransaction() : bool | |
{ | |
return $this->pdo->beginTransaction(); | |
} | |
public function commit() : bool | |
{ | |
$this->pdo->commit(); | |
} | |
public function rollBack() : bool | |
{ | |
$this->pdo->rollBack(); | |
} | |
public function getLastID($name = null) | |
{ | |
return $this->pdo->lastInsertId($name); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment