-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabase.php
More file actions
107 lines (94 loc) · 2.19 KB
/
Copy pathDatabase.php
File metadata and controls
107 lines (94 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<?php
namespace App\Core;
use PDO;
use PDOException;
/**
* Database Class - Singleton Pattern
*
* Quản lý kết nối database duy nhất trong toàn bộ application
* Design Pattern: Singleton
*
* @author Lê Văn Thuận (22070984)
*/
class Database
{
private static ?Database $instance = null;
private ?PDO $connection = null;
/**
* Private constructor để ngăn khởi tạo trực tiếp
*/
private function __construct()
{
try {
$dsn = sprintf(
'mysql:host=%s;dbname=%s;charset=%s',
DB_HOST,
DB_NAME,
DB_CHARSET
);
$this->connection = new PDO($dsn, DB_USER, DB_PASS, DB_OPTIONS);
} catch (PDOException $e) {
die('Database Connection Failed: ' . $e->getMessage());
}
}
/**
* Ngăn clone instance
*/
private function __clone() {}
/**
* Ngăn unserialize instance
*/
public function __wakeup()
{
throw new \Exception("Cannot unserialize singleton");
}
/**
* Lấy instance duy nhất của Database (Singleton)
*
* @return Database
*/
public static function getInstance(): Database
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Lấy PDO connection
*
* @return PDO
*/
public function getConnection(): PDO
{
return $this->connection;
}
/**
* Begin transaction
*/
public function beginTransaction(): bool
{
return $this->connection->beginTransaction();
}
/**
* Commit transaction
*/
public function commit(): bool
{
return $this->connection->commit();
}
/**
* Rollback transaction
*/
public function rollBack(): bool
{
return $this->connection->rollBack();
}
/**
* Get last insert ID
*/
public function lastInsertId(): string
{
return $this->connection->lastInsertId();
}
}