-
Notifications
You must be signed in to change notification settings - Fork 3
/
ray-di.php
63 lines (55 loc) · 1.87 KB
/
ray-di.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
<?php
use Ray\Di\AbstractModule;
use Ray\Di\Injector;
use Ray\Di\ProviderInterface;
require __DIR__ . '/psr-11-v2/vendor/autoload.php';
require __DIR__ . '/setup.php';
class DsnProvider implements ProviderInterface{
public function get(): string
{
return getenv('DB_DSN');
}
}
class UserProvider implements ProviderInterface
{
public function get(): string
{
return getenv('DB_USERNAME');
}
}
class PasswordProvider implements ProviderInterface
{
public function get(): string
{
return getenv('DB_PASSWORD');
}
}
$module = new class extends AbstractModule
{
protected function configure()
{
// Gives a dependency name to the constructor argument of PDO.
$this->bind(PDO::class)->toConstructor(PDO::class, ['dsn' => 'db_dsn', 'username' => 'db_username', 'password' => 'db_password']);
// Bind a Provider to each dependency name with toProvider() method
$this->bind()->annotatedWith('db_dsn')->toProvider(DsnProvider::class);
$this->bind()->annotatedWith('db_user')->toProvider(UserProvider::class);
$this->bind()->annotatedWith('db_password')->toProvider(PasswordProvider::class);
// Gives a dependency name to the constructor argument of Foo.
$this->bind(Foo::class)->toConstructor(Foo::CLASS, ['bar' => 'bar', 'baz' => 'baz']);
// Bind an insatance to each dependency name with toInstance() method.
$this->bind()->annotatedWith('bar')->toInstance('bar-wrong');
$this->bind()->annotatedWith('baz')->toInstance('baz-right');
}
};
// Redefine Foo $bar
$module->override(
new class extends AbstractModule {
protected function configure()
{
$this->bind()->annotatedWith('bar')->toInstance('bar-right');
}
}
);
$injector = new Injector($module);
echo "Ray.Di" . PHP_EOL;
output($injector, 'getInstance');