-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcallable.php
69 lines (56 loc) · 1.61 KB
/
callable.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
<?php declare(strict_types=1);
/**
* Closure Container
*/
class Container
{
private $services = [];
/**
* Register service
*/
public function add($serviceName, $service = null)
{
if(array_key_exists($serviceName, $this->services)) {
throw new \LogicException(sprintf('Service %s already instantiated', $serviceName));
}
if (is_callable($service)) {
$this->services[$serviceName] = $service();
return;
}
if (is_object($service)) {
$this->services[$serviceName] = $service;
return;
}
$this->services[$serviceName] = new $serviceName();
}
/**
* Get service
*
* @return void
*/
public function get($serviceName)
{
if (!isset($this->services[$serviceName])) {
throw new \Exception(sprintf('Service %s not found', $serviceName));
}
return $this->services[$serviceName];
}
}
class Foo{}
class FooBar{
private $logger;
public function setLogger($logger) { $this->logger = $logger; }
public function getLogger() { return $this->logger; }
}
$container = new Container();
$container->add(Foo::class);
// Register your complex services using closure
$container->add(FooBar::class, function () {
$fooBar = new FooBar();
$fooBar->setLogger(new class() {
public function info($message) { echo sprintf('Info: %s', $message); }
});
return $fooBar;
});
var_dump($container->get(Foo::class) instanceof Foo); // true
$container->get(FooBar::class)->getLogger()->info('vim + tmux + zsh = Awesome');