Skip to content

Commit 1423e34

Browse files
committed
documentation about method injection
fixes #11565
1 parent bda42b6 commit 1423e34

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

docs/guide/concept-di-container.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ Yii provides the DI container feature through the class [[yii\di\Container]]. It
1313
dependency injection:
1414

1515
* Constructor injection;
16+
* Method injection;
1617
* Setter and property injection;
1718
* PHP callable injection;
1819

@@ -39,6 +40,36 @@ $foo = new Foo($bar);
3940
```
4041

4142

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+
4273
### Setter and Property Injection <span id="setter-and-property-injection"></span>
4374

4475
Setter and property injection is supported through [configurations](concept-configurations.md).

0 commit comments

Comments
 (0)