-
Notifications
You must be signed in to change notification settings - Fork 0
/
greeter.php
71 lines (60 loc) · 1.37 KB
/
greeter.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
<?php
require __DIR__ . '/vendor/autoload.php';
use Ray\Di\AbstractModule;
use Ray\Di\Di\Qualifier;
use Ray\Di\ProviderInterface;
use Ray\Di\Injector;
#[Attribute, Qualifier]
class Message
{
}
#[Attribute, Qualifier]
class Count
{
}
class CountProvider implements ProviderInterface
{
public function get(): int
{
return 3;
}
}
class MessageProvider implements ProviderInterface
{
public function get(): string
{
return 'hello world';
}
}
class DemoModule extends AbstractModule
{
protected function configure()
{
$this->bind()->annotatedWith(Count::class)->toProvider(CountProvider::class);
$this->bind()->annotatedWith(Message::class)->toProvider(MessageProvider::class);
}
}
class Greeter
{
public function __construct(
#[Message] private string $message,
#[Count] private int $count
) {}
public function sayHello(): void
{
for ($i = 0; $i < $this->count ; $i++) {
echo $this->message . PHP_EOL;
}
}
}
/*
* Injector() takes one or more modules. Most applications
* will call this method exactly once, in their main() method.
*/
$injector = new Injector(new DemoModule);
/*
* Now that we've got the injector, we can build objects.
*/
$greeter = $injector->getInstance(Greeter::class);
// Prints "hello world" 3 times to the console.
$greeter->sayHello();