Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit bb810ab

Browse files
committed
Dependency injection
1 parent fe1a8f8 commit bb810ab

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed

‎Dependency_injection/index.php

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
<?php
2+
/**
3+
* Design pattern "Dependency injection" (Structural)
4+
* This is demo code
5+
* See for details: http://maxsite.org/page/php-di
6+
* https://en.wikipedia.org/wiki/Dependency_injection
7+
*/
8+
9+
// type Configuration
10+
interface ConfigurationInterface
11+
{
12+
public function getKey1();
13+
public function getKey2();
14+
}
15+
16+
// class for configuration
17+
class ConfigurationOne implements ConfigurationInterface
18+
{
19+
private $key1;
20+
private $key2;
21+
22+
public function __construct($key1, $key2)
23+
{
24+
$this->key1 = $key1;
25+
$this->key2 = $key2;
26+
}
27+
28+
public function getKey1()
29+
{
30+
return $this->key1;
31+
}
32+
33+
public function getKey2()
34+
{
35+
return $this->key2;
36+
}
37+
}
38+
39+
// Connection use Configuration data
40+
class Connection
41+
{
42+
private $configuration;
43+
44+
public function __construct(ConfigurationInterface $config)
45+
{
46+
$this->configuration = $config;
47+
}
48+
49+
// something to do
50+
public function run()
51+
{
52+
return [
53+
$this->configuration->getKey1(),
54+
$this->configuration->getKey2()
55+
];
56+
}
57+
}
58+
59+
/**
60+
* demo
61+
*/
62+
$config = new ConfigurationOne('myKey1', 'myKey2');
63+
$connection = new Connection($config);
64+
65+
echo '<pre>';
66+
print_r($connection->run());
67+
/*
68+
Array (
69+
[0] => myKey1
70+
[1] => myKey2
71+
)
72+
*/
73+
74+
# end of file

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ See details on http://maxsite.org/page/php-patterns
2020
* "Flyweight" (Structural)
2121
* "Proxy" (Structural)
2222
* "Template method" (Behavioral)
23+
* "Dependency injection" (Creational)
2324

2425

2526
(c) MaxSite.org, 2019, http://maxsite.org/

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /