1
|
|
|
<?php |
2
|
|
|
use League\Container\Container; |
3
|
|
|
use League\Container\ReflectionContainer; |
4
|
|
|
use Symfony\Component\HttpFoundation\Request; |
5
|
|
|
/** |
6
|
|
|
* Container setup |
7
|
|
|
*/ |
8
|
|
|
$container = new Container(); |
9
|
|
|
$container->delegate( |
10
|
|
|
new ReflectionContainer() // Auto-wiring |
11
|
|
|
); |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* set Request |
15
|
|
|
*/ |
16
|
|
|
$container->add(Request::class,Request::createFromGlobals()); |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* set Twig |
20
|
|
|
*/ |
21
|
|
|
$container->share(Twig_Environment::class) |
22
|
|
|
->withArgument(new Twig_Loader_Filesystem(__DIR__ . '/../app/views/')); |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* set Monolog |
26
|
|
|
*/ |
27
|
|
|
$container->share(Monolog\Logger::class) |
28
|
|
|
->withArgument('myLogger') |
29
|
|
|
; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* set Propel2 Logger |
33
|
|
|
*/ |
34
|
|
|
Propel\Runtime\Propel::getServiceContainer()->setLogger('defaultLogger', |
35
|
|
|
(new Monolog\Logger('defaultLogger')) |
36
|
|
|
->pushHandler(new Monolog\Handler\StreamHandler('php://stderr')) |
37
|
|
|
); |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* set Debug bar |
41
|
|
|
*/ |
42
|
|
|
$container->share(DebugBar\StandardDebugBar::class) |
|
|
|
|
43
|
|
|
->withMethodCall("addCollector",[ |
44
|
|
|
new DebugBar\Bridge\Twig\TwigCollector( |
45
|
|
|
new DebugBar\Bridge\Twig\TraceableTwigEnvironment( |
46
|
|
|
$container->get(Twig_Environment::class), |
47
|
|
|
new DebugBar\DataCollector\TimeDataCollector |
48
|
|
|
) |
49
|
|
|
) |
50
|
|
|
]) |
51
|
|
|
->withMethodCall("addCollector",[ |
52
|
|
|
new DebugBar\Bridge\Propel2Collector(Propel\Runtime\Propel::getConnection()) |
53
|
|
|
]) |
54
|
|
|
->withMethodCall("addCollector",[ |
55
|
|
|
new \DebugBar\Bridge\MonologCollector($container->get(Monolog\Logger::class)) |
56
|
|
|
]) |
57
|
|
|
; |
58
|
|
|
; |
59
|
|
|
|
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* inflector interfaces |
63
|
|
|
*/ |
64
|
|
|
|
65
|
|
|
$container->inflector(Psr\Log\LoggerAwareInterface::class) |
66
|
|
|
->invokeMethod('setLogger', [$container->get(Monolog\Logger::class)]); |
67
|
|
|
|
68
|
|
|
$container->inflector(Frameworkless\Controllers\PageInterface::class) |
69
|
|
|
->invokeMethod('setTwig', [$container->get(Twig_Environment::class)]) |
70
|
|
|
->invokeMethod('setDebugbar', [$container->get(DebugBar\StandardDebugBar::class)]) |
71
|
|
|
; |
72
|
|
|
|
73
|
|
|
|
74
|
|
|
App::getInstance()->import("DI", $container); |
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the interface: