-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path6-Dependency_Injection.php
More file actions
136 lines (97 loc) · 2.28 KB
/
6-Dependency_Injection.php
File metadata and controls
136 lines (97 loc) · 2.28 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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
<?php
/* Theoretical example of class dependency injection */
class Chest
{
protected $lock;
protected $isClosed;
// "Type-hinting" what class should be "expected upon injection" while the class contructs
public function __contruct(Lock $lock)
{
$this->lock = $lock;
}
// Optional function parameter
public function close($lock = true)
{
if($lock === true) {
$this->lock->lock();
}
$this->isClosed = true;
echo "close";
}
public function isClosed()
{
return $this->isClosed;
}
public function open()
{
if( $this->lock->isLocked() ) {
$this->lock->unLock();
}
$this->isClosed = false;
echo "open";
}
}
class Lock
{
protected $isLocked;
public function lock()
{
$this->isLocked = true;
}
public function unLock()
{
$this->isLocked = false;
}
public function isLocked()
{
return $this->isLocked;
}
}
// Dependency injection, by "giving" a specific class to an other class that requires it to run
$chest = new Chest(new Lock);
$chest->close();
$chest->open();
/* Real life example of dependency injection */
class Database
{
// A static property of the class
protected static $instance;
// We create a new static instance of the class itself
public static function getInstance()
{
if(!static::$instance) {
static::$instance = new self;
}
return static::$instance;
}
public function query($sql)
{
// PDO database driver
$this->pdo->prepare($sql)->execute();
}
}
class User
{
protected $db;
// "Type-hinting" what class should be "expected upon injection" while the class contructs
public function __contruct(Database $db)
{
$this->db = $db;
}
// GOOD dependency injection
public function create(array $data)
{
$this->db->query('INSERT INTO `users` ...');
}
// BAD dependency injection becuase of "tight coupling", which makes it harder to chance in future
public function create(array $data)
{
$db = Database::getInstance();
$db->query('INSERT INTO `users` ...');
}
}
// Dependency injection, by "giving" a specific class to an other class that requires it to run
$user = new User(new Database);
$user->create([
'username' => 'John'
]);