-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsingleton.php
More file actions
62 lines (48 loc) · 1.71 KB
/
singleton.php
File metadata and controls
62 lines (48 loc) · 1.71 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
<?php
class Singleton
{
// instance PDO di simpan sebagai variabel static
protected static ?PDO $_singleton = null;
private string $name;
private string $user;
private string $password;
public function __construct(string $name, string $user, string $password)
{
$this->name = $name;
$this->user = $user;
$this->password = $password;
$this->setConnection();
}
public static function getSingleton() : ?PDO
{
// di sini proses pengecekan jika variabel $_singleton sudah terdapat instance pdo sebelumnnya maka gunakan itu
if (isset(self::$_singleton)) {
return self::$_singleton;
}
// buat instance pdo baru jika tidak ada instance sebelumnnya
$_instance = new Singleton(name: 'singleton', user: 'test', password: 'pass');
return $_instance->isConnecting();
}
private function setConnection() : void
{
try {
self::$_singleton = new PDO(dsn: "mysql:host=localhost:3306;dbname={$this->name}", username: $this->user, password: $this->password);
self::$_singleton->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (\PDOException $e) {
echo "Error". PHP_EOL;
echo $e->getMessage(). PHP_EOL;
self::$_singleton = null;
exit;
}
}
private function isConnecting() : ?PDO
{
return self::$_singleton;
}
}
// gunakan identical operator untuk membandingkan kedua instance sekaligus tipenya
$db1 = Singleton::getSingleton();
$db2 = Singleton::getSingleton();
var_dump($db1 === $db2); // true
// atau gunakan instanceof
var_dump($db1 instanceof $db2); // true