-
Notifications
You must be signed in to change notification settings - Fork 0
/
container_3.php
119 lines (95 loc) · 2.04 KB
/
container_3.php
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
<?php
/**
*=============================================================
* <container_3.php>
* Object Oriented Programming: Dependency Injection Container in PHP
* Using shared instances
* @author Muhammad Anwar Hussain<[email protected]>
* Created on: 15th June 2019
* ============================================================
*/
trait Trademarks
{
public function logo($logo)
{
echo get_class($this) . '\'s '. ucfirst($logo) .'<br>';
}
public function hallmark($hmark)
{
echo get_class($this) . '\'s '. ucfirst($hmark) .'<br>';
}
}
class Foo
{
use Trademarks;
}
class Bar
{
use Trademarks;
}
class Baz
{
use Trademarks;
}
class Registration
{
protected $data = [];
function __construct(array $data = [])
{
$this->data = $data;
}
public function register($key, $subkey)
{
$this->data['instantiate'] = new $this->data[$key][$subkey];
}
public function execute($key, $subkey)
{
$value = $this->data[$key][$subkey];
$this->data['instantiate']->$value($value);
}
}
class Container
{
protected $data = [];
static protected $instance;
public function __construct(array $data = [])
{
$this->data = $data;
}
public function getInstance($key)
{
if (!isset(self::$instance))
{ $array = $this->data;
array_shift($array);
self::$instance = new $this->data[$key]($array);
}
return self::$instance;
}
}
[$register, $companies, $trademarks] = ['register', 'company', 'trademark'];
$data = array(
$register => 'Registration',
$companies => array(
'foo' => 'Foo',
'bar' => 'Bar',
'baz' => 'Baz',
),
$trademarks => array(
'logo' => 'logo',
'hmark' => 'hallmark',
),
);
$c = new Container($data);
$r = $c->getInstance($register);
$ckeys = array_keys($data[$companies]); // $ckeys = ['foo', 'bar', 'baz'];
$mkeys = array_keys($data[$trademarks]); // $mkeys = ['logo', 'hmark'];
for($i = 0; $i < count($ckeys); $i++)
{
$r->register($companies, $ckeys[$i]);
for($j = 0; $j < count($mkeys); $j++)
{
$r->execute($trademarks, $mkeys[$j]);
}
echo '<br>';
}
?>