File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change @@ -13,6 +13,7 @@ Yii provides the DI container feature through the class [[yii\di\Container]]. It
13
13
dependency injection:
14
14
15
15
* Constructor injection;
16
+ * Method injection;
16
17
* Setter and property injection;
17
18
* PHP callable injection;
18
19
@@ -39,6 +40,36 @@ $foo = new Foo($bar);
39
40
```
40
41
41
42
43
+ ### Method Injection <span id =" method-injection " ></span >
44
+
45
+ Usually the dependencies of a class are passed to the constructor and are available inside of the class during the whole lifecycle.
46
+ With Method Injection it is possible to provide a dependency that is only needed by a single method of the class
47
+ and passing it to the constructor may not be possible or may cause too much overhead in the majority of use cases.
48
+
49
+ A class method can be defined like the ` doSomething() ` method in the following example:
50
+
51
+ ``` php
52
+ class MyClass extends \yii\base\Component
53
+ {
54
+ public function __construct(/*Some lightweight dependencies here*/, $config = [])
55
+ {
56
+ // ...
57
+ }
58
+
59
+ public function doSomething($param1, \my\heavy\Dependency $something)
60
+ {
61
+ // do something with $something
62
+ }
63
+ }
64
+ ```
65
+
66
+ You may call that method either by passing an instance of ` \my\heavy\Dependency ` yourself or using [[ yii\di\Container::invoke()]] like the following:
67
+
68
+ ``` php
69
+ $obj = new MyClass(/*...*/);
70
+ Yii::$container->invoke([$obj, 'doSomethingWithHeavyDependency'], ['param1' => 42]); // $something will be provided by the DI container
71
+ ```
72
+
42
73
### Setter and Property Injection <span id =" setter-and-property-injection " ></span >
43
74
44
75
Setter and property injection is supported through [ configurations] ( concept-configurations.md ) .
You can’t perform that action at this time.
0 commit comments