NEW: Creating Database.php class to assign all responsability of DB connection in this archive.
This commit is contained in:
parent
892537628a
commit
f4b12aa743
|
|
@ -0,0 +1,42 @@
|
|||
<?php
|
||||
|
||||
namespace App\models;
|
||||
|
||||
class Database
|
||||
{
|
||||
|
||||
private $hostname;
|
||||
private $username;
|
||||
private $password;
|
||||
private $database;
|
||||
private static $connection = null;
|
||||
public function __construct()
|
||||
{
|
||||
|
||||
$this->hostname = $_ENV['DB_HOST'];
|
||||
$this->username = $_ENV['DB_USER'];
|
||||
$this->password = $_ENV['DB_PASSWORD'];
|
||||
$this->database = $_ENV['DB'];
|
||||
}
|
||||
|
||||
public function dbConnect()
|
||||
{
|
||||
|
||||
|
||||
if (self::$connection === null) {
|
||||
try {
|
||||
self::$connection = new \PDO(
|
||||
'mysql:host=' . $this->hostname . ';' .
|
||||
'dbname=' . $this->database . ';' .
|
||||
'charset=utf8mb4',
|
||||
$this->username,
|
||||
$this->password
|
||||
);
|
||||
self::$connection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
|
||||
} catch (\PDOException $e) {
|
||||
return json_encode(['error' => 'Erro na conexão com o banco ' . $e->getMessage()]);
|
||||
}
|
||||
}
|
||||
return self::$connection;
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue